Skip to content

Commit

Permalink
converted Counter to typegoose
Browse files Browse the repository at this point in the history
  • Loading branch information
andrefs committed Oct 18, 2023
1 parent 3a9bef7 commit 5cf6fa5
Showing 1 changed file with 33 additions and 45 deletions.
78 changes: 33 additions & 45 deletions src/models/Counter.ts
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 };

0 comments on commit 5cf6fa5

Please sign in to comment.