thread-relation.ts 1.7 KB

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