diff --git a/package-lock.json b/package-lock.json index be7fc71..9ca6e02 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3831,9 +3831,9 @@ } }, "node_modules/micromatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.7.tgz", - "integrity": "sha512-LPP/3KorzCwBxfeUuZmaR6bG2kdeHSbe0P2tY3FLRU4vYrjYz5hI4QZwV0njUx3jeuKe67YukQ1LSPZBKDqO/Q==", + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", "dev": true, "license": "MIT", "dependencies": { diff --git a/src/api/models/blogModel.ts b/src/api/models/blogModel.ts index 76fe285..f1778e6 100644 --- a/src/api/models/blogModel.ts +++ b/src/api/models/blogModel.ts @@ -1,4 +1,6 @@ -import mongoose, { Schema } from "mongoose"; +import mongoose, { HydratedDocument, Schema } from "mongoose"; +import { ITag, TagType } from "./tags"; +import { IUser } from "./userModel"; /** Hardcoded values so relative orders are in sync with db */ export enum BlogStatus { @@ -18,6 +20,7 @@ export interface IBlog { status: BlogStatus; category_id: number; cover: string | null; + tags: ITag[]; views: number; likes: number; meta_title: string; @@ -63,6 +66,22 @@ const blogSchema = new Schema( type: String, default: null, }, + tags: { + type: [ + { + tag_type: { type: Number, enum: TagType }, + users: [ + { + type: mongoose.Schema.Types.ObjectId, + ref: "user", + }, + ], + tag_name: { + type: String, + }, + }, + ], + }, views: { type: Number, default: 0, @@ -98,6 +117,20 @@ const blogSchema = new Schema( }, ); +// Middleware to auto-populate tags on find queries +function find_prehook( + this: mongoose.Query, + next: mongoose.CallbackWithoutResultAndOptionalError, +) { + this.populate<{ tags: { users: HydratedDocument } }>( + "tags.users", + "_id name email bio", + ); + next(); +} + +blogSchema.pre(/^find/, find_prehook); + const Blog = mongoose.model("blog", blogSchema); export { Blog }; diff --git a/src/api/models/tags.ts b/src/api/models/tags.ts new file mode 100644 index 0000000..0b4ae71 --- /dev/null +++ b/src/api/models/tags.ts @@ -0,0 +1,23 @@ +import mongoose from "mongoose"; + +export enum TagType { + Author, + Designer, + Illustrator, + Photographer, + Other, +} + +interface BaseTag { + tag_type: Exclude; + users: mongoose.Schema.Types.ObjectId[]; +} + +// TODO: discuss if it is required or we can remove it (by only extending the enum for this stuff) +interface OtherTag { + tag_type: TagType.Other; + tag_name: string; + users: mongoose.Schema.Types.ObjectId[]; +} + +export type ITag = BaseTag | OtherTag;