2
0

thread-relation.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { addDays } from 'date-fns';
  2. import { type Document, Schema, type PaginateModel } from 'mongoose';
  3. import mongoosePaginate from 'mongoose-paginate-v2';
  4. import { getOrCreateModel } from '~/server/util/mongoose-utils';
  5. import { type IThreadRelation, ThreadType } from '../../interfaces/thread-relation';
  6. const DAYS_UNTIL_EXPIRATION = 3;
  7. const generateExpirationDate = (): Date => {
  8. return addDays(new Date(), DAYS_UNTIL_EXPIRATION);
  9. };
  10. export interface ThreadRelationDocument extends IThreadRelation, Document {
  11. updateThreadExpiration(): Promise<void>;
  12. }
  13. interface ThreadRelationModel extends PaginateModel<ThreadRelationDocument> {
  14. getExpiredThreadRelations(limit?: number): Promise<ThreadRelationDocument[] | undefined>;
  15. }
  16. const schema = new Schema<ThreadRelationDocument, ThreadRelationModel>({
  17. userId: {
  18. type: Schema.Types.ObjectId,
  19. ref: 'User',
  20. required: true,
  21. },
  22. aiAssistant: {
  23. type: Schema.Types.ObjectId,
  24. ref: 'AiAssistant',
  25. },
  26. threadId: {
  27. type: String,
  28. required: true,
  29. unique: true,
  30. },
  31. title: {
  32. type: String,
  33. },
  34. type: {
  35. type: String,
  36. enum: Object.values(ThreadType),
  37. required: true,
  38. },
  39. expiredAt: {
  40. type: Date,
  41. default: generateExpirationDate,
  42. required: true,
  43. },
  44. }, {
  45. timestamps: { createdAt: true, updatedAt: true },
  46. });
  47. schema.plugin(mongoosePaginate);
  48. schema.statics.getExpiredThreadRelations = async function(limit?: number): Promise<ThreadRelationDocument[] | undefined> {
  49. const currentDate = new Date();
  50. const expiredThreadRelations = await this.find({ expiredAt: { $lte: currentDate } }).limit(limit ?? 100).exec();
  51. return expiredThreadRelations;
  52. };
  53. schema.methods.updateThreadExpiration = async function(): Promise<void> {
  54. this.expiredAt = generateExpirationDate();
  55. await this.save();
  56. };
  57. export default getOrCreateModel<ThreadRelationDocument, ThreadRelationModel>('ThreadRelation', schema);