user.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { Provide, Scope, ScopeEnum } from "@midwayjs/decorator";
  2. import AppError from "@/utils/common/AppError";
  3. import ErrNo from "@/constants/errorEnum";
  4. import BaseService from "@/apis/service/base";
  5. import ModelName from "@/constants/dbEnum";
  6. import { UserDocument } from "@/apis/model/User";
  7. // 单例
  8. @Provide()
  9. @Scope(ScopeEnum.Singleton)
  10. export default class UserService extends BaseService {
  11. private get UserModel() {
  12. return this.getModel<UserDocument>(ModelName.User);
  13. }
  14. async login(username: string, password: string) {
  15. if (username === "zhangsan" && password === "123") {
  16. // 测试 redis
  17. await this.redisService.set("foo", "bar123");
  18. const result = await this.redisService.get("foo");
  19. // 测试 cache
  20. await this.cacheService.set("user-123", "张三");
  21. const name = await this.cacheService.get("user-123");
  22. return `userID:zhangsan-123_${result}_${name}`;
  23. }
  24. throw new AppError("用户名或密码错误", ErrNo.LOGIN_FAIL);
  25. }
  26. async test() {
  27. const doc = new this.UserModel({
  28. name: "Bill",
  29. email: "bill@initech.com",
  30. avatar: "https://i.imgur.com/dM7Thhn.png",
  31. });
  32. await doc.save();
  33. }
  34. }