Skip to content

Commit

Permalink
Merge pull request #116 from dvishal485/main
Browse files Browse the repository at this point in the history
basic tag system
  • Loading branch information
m-siya authored Sep 10, 2024
2 parents 57ace3a + 2de5736 commit 1beb500
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 4 deletions.
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 34 additions & 1 deletion src/api/models/blogModel.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -18,6 +20,7 @@ export interface IBlog {
status: BlogStatus;
category_id: number;
cover: string | null;
tags: ITag[];
views: number;
likes: number;
meta_title: string;
Expand Down Expand Up @@ -63,6 +66,22 @@ const blogSchema = new Schema<IBlog>(
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,
Expand Down Expand Up @@ -98,6 +117,20 @@ const blogSchema = new Schema<IBlog>(
},
);

// Middleware to auto-populate tags on find queries
function find_prehook(
this: mongoose.Query<IBlog[], IBlog>,
next: mongoose.CallbackWithoutResultAndOptionalError,
) {
this.populate<{ tags: { users: HydratedDocument<IUser> } }>(
"tags.users",
"_id name email bio",
);
next();
}

blogSchema.pre(/^find/, find_prehook);

const Blog = mongoose.model<IBlog>("blog", blogSchema);

export { Blog };
23 changes: 23 additions & 0 deletions src/api/models/tags.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import mongoose from "mongoose";

export enum TagType {
Author,
Designer,
Illustrator,
Photographer,
Other,
}

interface BaseTag {
tag_type: Exclude<TagType, TagType.Other>;
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;

0 comments on commit 1beb500

Please sign in to comment.