-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
45 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,54 +1,42 @@ | ||
import { Schema, model, Model, Document } from 'mongoose'; | ||
import { createLogger } from '@derzis/common'; | ||
const log = createLogger('Counter'); | ||
import { | ||
ReturnModelType, | ||
getModelForClass, | ||
index, | ||
prop, | ||
} from '@typegoose/typegoose'; | ||
|
||
export interface ICounter { | ||
name: String; | ||
value: number; | ||
} | ||
|
||
interface ICounterDocument extends ICounter, Document { } | ||
interface ICounterModel extends Model<ICounterDocument> { | ||
genId: (name: String) => Promise<number>; | ||
} | ||
@index({ name: 1 }) | ||
class CounterClass { | ||
@prop({ required: true }) | ||
name!: string; | ||
|
||
interface ICounterDocument extends ICounter, Document { } | ||
@prop({ required: true, default: 0 }) | ||
value!: number; | ||
|
||
const CounterSchema: Schema<ICounterDocument> = new Schema( | ||
{ | ||
name: { | ||
type: String, | ||
required: true, | ||
}, | ||
value: { | ||
type: Number, | ||
required: true, | ||
default: 0, | ||
}, | ||
}, | ||
{ timestamps: true } | ||
); | ||
public static async genId( | ||
this: ReturnModelType<typeof CounterClass>, | ||
name: string | ||
) { | ||
const c = await this.findOneAndUpdate( | ||
{ name: 'jobs' }, | ||
{ $inc: { value: 1 } }, | ||
{ | ||
upsert: true, | ||
returnDocument: 'after', | ||
lean: true, | ||
projection: 'value', | ||
} | ||
); | ||
log.debug(`Generated job id ${c!.value}`); | ||
return c!.value; | ||
} | ||
} | ||
|
||
CounterSchema.index({ | ||
name: 1, | ||
const Counter = getModelForClass(CounterClass, { | ||
schemaOptions: { timestamps: true }, | ||
}); | ||
|
||
CounterSchema.statics.genId = async function(name: string) { | ||
const c = await this.findOneAndUpdate( | ||
{ name: 'jobs' }, | ||
{ $inc: { value: 1 } }, | ||
{ | ||
upsert: true, | ||
returnDocument: 'after', | ||
lean: true, | ||
projection: 'value', | ||
} | ||
); | ||
log.debug(`Generated job id ${c.value}`); | ||
return c.value; | ||
}; | ||
|
||
export const Counter = model<ICounterDocument, ICounterModel>( | ||
'Counter', | ||
CounterSchema | ||
); | ||
export { Counter, CounterClass }; |