wangzhibo
5 天以前 50e5cdbaceee71f000341a434620d10a87b582f5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { Init, Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { Equal, Repository } from 'typeorm';
import { UserAddressEntity } from '../entity/address';
import { InjectEntityModel } from '@midwayjs/typeorm';
 
/**
 * 地址
 */
@Provide()
export class UserAddressService extends BaseService {
  @InjectEntityModel(UserAddressEntity)
  userAddressEntity: Repository<UserAddressEntity>;
 
  @Inject()
  ctx;
 
  @Init()
  async init() {
    await super.init();
    this.setEntity(this.userAddressEntity);
  }
 
  /**
   * 列表信息
   */
  async list() {
    return this.userAddressEntity
      .createQueryBuilder()
      .where('userId = :userId ', { userId: this.ctx.user.id })
      .addOrderBy('isDefault', 'DESC')
      .getMany();
  }
 
  /**
   * 修改之后
   * @param data
   * @param type
   */
  async modifyAfter(data: any, type: 'add' | 'update' | 'delete') {
    if (type == 'add' || type == 'update') {
      if (data.isDefault) {
        await this.userAddressEntity
          .createQueryBuilder()
          .update()
          .set({ isDefault: false })
          .where('userId = :userId ', { userId: this.ctx.user.id })
          .andWhere('id != :id', { id: data.id })
          .execute();
      }
    }
  }
 
  /**
   * 默认地址
   */
  async default(userId) {
    return await this.userAddressEntity.findOneBy({
      userId: Equal(userId),
      isDefault: true,
    });
  }
}