| 1 | /* |
| 2 | * @Author: nevin |
| 3 | * @Date: 2021-12-24 13:49:52 |
| 4 | * @LastEditors: nevin |
| 5 | * @LastEditTime: 2024-08-30 15:01:55 |
| 6 | * @Description: 自增ID |
| 7 | */ |
| 8 | import { Model } from 'mongoose'; |
| 9 | import { InjectModel } from '@nestjs/mongoose'; |
| 10 | import { Injectable } from '@nestjs/common'; |
| 11 | import { Id, IdDocument } from './id.schema'; |
| 12 | |
| 13 | @Injectable() |
| 14 | export class IdService { |
| 15 | constructor( |
| 16 | @InjectModel(Id.name) private readonly idModel: Model<IdDocument>, |
| 17 | ) {} |
| 18 | |
| 19 | /** |
| 20 | * @description: 创建id |
| 21 | * @param {string} id_name id名称 |
| 22 | * @param {number} id_value id |
| 23 | * @return: Promise<number> |
| 24 | */ |
| 25 | public async createId<T extends string | number>( |
| 26 | id_name: string, |
| 27 | id_value: number, |
| 28 | id_type: T, |
| 29 | ): Promise<T> { |
| 30 | const fadArgs = { |
| 31 | query: { |
| 32 | id_name, |
| 33 | }, |
| 34 | update: { |
| 35 | $inc: { id_value: 1 }, |
| 36 | $set: { update_time: new Date() }, |
| 37 | }, |
| 38 | options: { new: true }, |
| 39 | }; |
| 40 | let newId = await this.idModel |
| 41 | .findOneAndUpdate(fadArgs.query, fadArgs.update, fadArgs.options) |
| 42 | .exec(); |
| 43 | if (newId) { |
| 44 | return <T>newId.id_value; |
| 45 | } |
| 46 | const createdUser = new this.idModel({ id_name, id_value }); |
| 47 | newId = await createdUser.save(); |
| 48 | |
| 49 | const id = |
| 50 | typeof id_type === 'string' ? newId.id_value.toString() : newId.id_value; |
| 51 | |
| 52 | return <T>id; |
| 53 | } |
| 54 | } |
| 55 |