|
| 1 | +/* |
| 2 | + * Copyright © 2024 Hexastack. All rights reserved. |
| 3 | + * |
| 4 | + * Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms: |
| 5 | + * 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission. |
| 6 | + * 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file). |
| 7 | + */ |
| 8 | + |
| 9 | +import { ModelDefinition, Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; |
| 10 | +import { Exclude, Transform, Type } from 'class-transformer'; |
| 11 | +import { Schema as MongooseSchema } from 'mongoose'; |
| 12 | + |
| 13 | +import { BaseSchema } from '@/utils/generics/base-schema'; |
| 14 | +import { LifecycleHookManager } from '@/utils/generics/lifecycle-hook-manager'; |
| 15 | +import { |
| 16 | + TFilterPopulateFields, |
| 17 | + THydratedDocument, |
| 18 | +} from '@/utils/types/filter.types'; |
| 19 | + |
| 20 | +import { Message } from './message.schema'; |
| 21 | +import { Subscriber } from './subscriber.schema'; |
| 22 | + |
| 23 | +@Schema({ timestamps: true }) |
| 24 | +export class ThreadStub extends BaseSchema { |
| 25 | + @Prop({ |
| 26 | + type: String, |
| 27 | + unique: true, |
| 28 | + required: true, |
| 29 | + }) |
| 30 | + title: string; |
| 31 | + |
| 32 | + @Prop({ |
| 33 | + type: MongooseSchema.Types.ObjectId, |
| 34 | + required: false, |
| 35 | + ref: 'Subscriber', |
| 36 | + }) |
| 37 | + subscriber?: unknown; |
| 38 | +} |
| 39 | + |
| 40 | +@Schema({ timestamps: true }) |
| 41 | +export class Thread extends ThreadStub { |
| 42 | + @Transform(({ obj }) => obj.subscriber?.toString()) |
| 43 | + subscriber: string; |
| 44 | + |
| 45 | + @Exclude() |
| 46 | + messages?: never; |
| 47 | +} |
| 48 | + |
| 49 | +@Schema({ timestamps: true }) |
| 50 | +export class ThreadFull extends ThreadStub { |
| 51 | + @Type(() => Subscriber) |
| 52 | + subscriber: Subscriber; |
| 53 | + |
| 54 | + @Type(() => Message) |
| 55 | + messages?: Message[]; |
| 56 | +} |
| 57 | + |
| 58 | +export type ThreadDocument = THydratedDocument<Thread>; |
| 59 | + |
| 60 | +export const ThreadModel: ModelDefinition = LifecycleHookManager.attach({ |
| 61 | + name: Thread.name, |
| 62 | + schema: SchemaFactory.createForClass(ThreadStub), |
| 63 | +}); |
| 64 | + |
| 65 | +ThreadModel.schema.virtual('messages', { |
| 66 | + ref: 'Message', |
| 67 | + localField: '_id', |
| 68 | + foreignField: 'thread', |
| 69 | + justOne: false, |
| 70 | +}); |
| 71 | + |
| 72 | +export default ThreadModel.schema; |
| 73 | + |
| 74 | +export type ThreadPopulate = keyof TFilterPopulateFields<Thread, ThreadStub>; |
| 75 | + |
| 76 | +export const THREAD_POPULATE: ThreadPopulate[] = ['messages', 'subscriber']; |
0 commit comments