-
Notifications
You must be signed in to change notification settings - Fork 21
/
Category.ts
141 lines (130 loc) · 3.68 KB
/
Category.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import Subcategory, {
TSubcategoryDocument,
subcategoryDocumentToSubcategory,
} from "./Subcategory";
import { TCategory, TSubcategory } from "@upswyng/types";
import mongoose, { Document, Schema } from "mongoose";
import { ObjectId } from "bson";
import removeUndefinedFields from "../utility/removeUndefinedFields";
export interface TCategoryDocument extends Document {
_id: ObjectId;
color: string;
createdAt: Date;
lastModifiedAt: Date;
name: string;
stub: string;
subcategories: ObjectId[] | TSubcategoryDocument[];
}
export async function categoryDocumentToCategory(
d: TCategoryDocument
): Promise<TCategory | null> {
let c = d;
if (d.toObject) {
c = d.toObject();
} else {
// console.warn(
// `\`categoryToDocumentCategory\` received category which does not appear to be a Mongoose Document [${Object.keys(
// d
// )}]:\n${JSON.stringify(d, null, 2)}`
// );
if (d.hasOwnProperty("_bsontype")) {
// console.warn("This appears to be an ObjectId");
// console.trace();
return null;
}
}
const result = {
...c,
_id: c._id.toHexString(),
subcategories: (
await Promise.all(
((c.subcategories || []) as TSubcategoryDocument[]).map(
subcategoryDocumentToSubcategory
)
)
).filter(Boolean),
};
removeUndefinedFields(result);
return result;
}
const CategorySchema = new Schema<TCategoryDocument>({
name: { type: String, required: true },
stub: {
type: String,
lowercase: true,
required: true,
trim: true,
unique: true,
},
color: String,
subcategories: [
{
type: Schema.Types.ObjectId,
ref: "Subcategory",
},
],
createdAt: { type: Date, default: Date.now, required: true },
lastModifiedAt: { type: Date, default: Date.now, required: true },
});
CategorySchema.statics.findOrCreate = async function(
name: string,
stub: string,
// only used to update the color;
// will not create two categories if the only thing different is the color
color?: string
): Promise<TCategoryDocument> {
const result = await this.findOne({ name, stub }).populate("subcategories");
if (result) {
result.color = color;
return result;
} else {
return new this({ name, stub, color, subcategories: [] });
}
};
CategorySchema.statics.getCategoryList = async function(): Promise<
TCategoryDocument[]
> {
return await this.find().populate("subcategories");
};
CategorySchema.statics.getByStub = async function(
stub: string,
includeDeletedResources: boolean = false
): Promise<TCategoryDocument | null> {
const result = await this.findOne({ stub }).populate({
path: "subcategories",
populate: { path: "resources" },
});
if (result && !includeDeletedResources) {
result.subcategories.forEach(subcategory => {
subcategory.resources = subcategory.resources.filter(r => !r.deleted);
});
}
return result;
};
/**
* Creates or finds an existing subcategory by its name and adds
* it as a child of this category
*/
(CategorySchema.methods as any).addSubcategory = async function(
subcategoryName: string,
subcategoryStub: string
) {
const subcategory = await Subcategory.findOrCreate(
subcategoryName,
subcategoryStub,
this._id
);
await (subcategory as any).save();
this.subcategories.push((subcategory as any)._id);
await this.save();
};
const Category = mongoose.model<TCategoryDocument>("Category", CategorySchema);
export default Category as typeof Category & {
findOrCreate: (
name: string,
stub: string,
color?: string
) => Promise<TCategoryDocument>;
getCategoryList: () => Promise<TCategoryDocument[]>;
getByStub: (stub: string) => Promise<TCategoryDocument | null>;
};