thread-relation.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { addDays } from 'date-fns';
  2. import type mongoose from 'mongoose';
  3. import { type Model, type Document, Schema } from 'mongoose';
  4. import { getOrCreateModel } from '~/server/util/mongoose-utils';
  5. const DAYS_UNTIL_EXPIRATION = 3;
  6. const generateExpirationDate = (): Date => {
  7. return addDays(new Date(), DAYS_UNTIL_EXPIRATION);
  8. };
  9. interface ThreadRelation {
  10. userId: mongoose.Types.ObjectId;
  11. threadId: string;
  12. expiredAt: Date;
  13. }
  14. interface ThreadRelationDocument extends ThreadRelation, Document {
  15. updateThreadExpiration(): Promise<void>;
  16. }
  17. interface ThreadRelationModel extends Model<ThreadRelationDocument> {
  18. getExpiredThreadRelations(limit?: number): Promise<ThreadRelationDocument[] | undefined>;
  19. }
  20. const schema = new Schema<ThreadRelationDocument, ThreadRelationModel>({
  21. userId: {
  22. type: Schema.Types.ObjectId,
  23. ref: 'User',
  24. required: true,
  25. },
  26. threadId: {
  27. type: String,
  28. required: true,
  29. unique: true,
  30. },
  31. expiredAt: {
  32. type: Date,
  33. default: generateExpirationDate,
  34. required: true,
  35. },
  36. });
  37. schema.statics.getExpiredThreadRelations = async function(limit?: number): Promise<ThreadRelationDocument[] | undefined> {
  38. const currentDate = new Date();
  39. const expiredThreadRelations = await this.find({ expiredAt: { $lte: currentDate } }).limit(limit ?? 100).exec();
  40. return expiredThreadRelations;
  41. };
  42. schema.methods.updateThreadExpiration = async function(): Promise<void> {
  43. this.expiredAt = generateExpirationDate();
  44. await this.save();
  45. };
  46. export default getOrCreateModel<ThreadRelationDocument, ThreadRelationModel>('ThreadRelation', schema);