/
githubmirror
/
hexo
Обзор
Документация
Войти
/
githubmirror
/
hexo
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
lib/models/category.ts
83 строки
2 KB
D-Sketon
perf(PostCategory/PostTag): add binary relation index for performance (#5605)
06 фев 2025, 12:54
Не верифицирован
06 фев 2025, 12:54
4362bf4
Код
Авторство
О чём код?
import warehouse from 'warehouse'; import { slugize, full_url_for } from 'hexo-util'; import type Hexo from '../hexo'; import type { CategorySchema } from '../types'; export = (ctx: Hexo) => { const Category = new warehouse.Schema<CategorySchema>({ name: {type: String, required: true}, parent: { type: warehouse.Schema.Types.CUID, ref: 'Category'} }); Category.virtual('slug').get(function() { let name = this.name; if (!name) return; let str = ''; if (this.parent) { const parent = ctx.model('Category').findById(this.parent); str += `${parent.slug}/`; } const map = ctx.config.category_map || {}; name = map[name] || name; str += slugize(name, {transform: ctx.config.filename_case}); return str; }); Category.virtual('path').get(function() { let catDir = ctx.config.category_dir; if (catDir === '/') catDir = ''; if (!catDir.endsWith('/')) catDir += '/'; return `${catDir + this.slug}/`; }); Category.virtual('permalink').get(function() { return full_url_for.call(ctx, this.path); }); Category.virtual('posts').get(function() { const ReadOnlyPostCategory = ctx._binaryRelationIndex.post_category; const ids = ReadOnlyPostCategory.find({category_id: this._id}).map(item => item.post_id); return ctx.locals.get('posts').find({ _id: {$in: ids} }); }); Category.virtual('length').get(function() { const ReadOnlyPostCategory = ctx._binaryRelationIndex.post_category; return ReadOnlyPostCategory.find({category_id: this._id}).length; }); // Check whether a category exists Category.pre('save', (data: CategorySchema) => { const { name, parent } = data; if (!name) return; const Category = ctx.model('Category'); const cat = Category.findOne({ name, parent: parent || {$exists: false} }, {lean: true}); if (cat) { throw new Error(`Category \`${name}\` has already existed!`); } }); // Remove PostCategory references Category.pre('remove', (data: CategorySchema) => { const PostCategory = ctx.model('PostCategory'); return PostCategory.remove({category_id: data._id}); }); return Category; };