corgi/src/models/content/Article.ts

178 lines
3.3 KiB
TypeScript

import {
getModelForClass,
index,
modelOptions,
prop
} from '@typegoose/typegoose'
import { dbconn } from 'decorators/dbconn'
// @ts-ignore
import findOrCreate from 'mongoose-findorcreate'
import { Base, TimeStamps } from '@typegoose/typegoose/lib/defaultClasses'
import { checkJson, noJson } from '../../decorators/nojson'
import { BaseModule } from '../Base'
const jsonExcludeKeys = ['updatedAt', '__v']
const saveExcludeKeys = ['createdAt', 'updatedAt', '__v', '_id']
export class ArticleAttachmemt {
/**
* 图片路径
* @type {string}
*/
@prop()
public url: string
/**
* 图片描述
* @type {string}
*/
@prop()
public desc: string
/**
* 排序
* @type {number}
*/
@prop()
public sortno: number
/**
* 是否用作标题图
* @type {boolean}
*/
@prop({default: false})
public isMain: boolean
}
/**
* 通用文章
*/
interface ArticleClass extends Base, TimeStamps {
}
@dbconn()
@index({'tags': 1}, {unique: false})
@modelOptions({ schemaOptions: { collection: 'articles', timestamps: true } })
class ArticleClass extends BaseModule {
/**
* 标题
* @type {string}
*/
@prop({ required: true })
public title!: string
/**
* 用于显示的 类型
* @type {string}
*/
@prop()
public type: string
/**
* 内容
* @type {string}
*/
@prop()
public content: string
/**
* 摘要
* @type {string}
*/
@prop()
public summary: string
/**
* 内容相关时间, 一般和createAt相同
* @type {number}
*/
@prop()
public displayTime: number
/**
* 作者
* @type {string}
*/
@prop()
public author: string
/**
* 来源
* @type {string}
*/
@prop()
public source: string
/**
* 来源链接
* @type {string}
*/
@prop()
public sourceUrl: string
@prop({_id: false, type: () => [ArticleAttachmemt]})
public attachments: ArticleAttachmemt[]
/**
* @type {string[]}
*/
@prop({ type: () => [String] })
public tags: string[]
/**
* 关键字
* @type {string[]}
*/
@prop({ type: () => [String] })
public keywords: string[]
/**
* 是否删除
* @type {boolean}
*/
@noJson()
@prop({default: false})
public deleted: boolean
@noJson()
@prop()
public deleteTime: Date
/**
* 自定义排序字段
* @type {number}
*/
@prop({default: 0})
public sortno: number
/**
* 创建人
* @type {string}
*/
@prop()
public createdBy: string
public updateFromReq(data: any) {
for (let key in data) {
if (saveExcludeKeys.indexOf(key) == -1) {
this[key] = data[key]
}
}
}
public toJson() {
let result: any = {}
for (let key in this) {
if (checkJson(this, key+'' ) && jsonExcludeKeys.indexOf(key) == -1) {
result[key] = this[key]
}
}
return result
}
public static parseQueryParam(params) {
let {timeBegin, timeEnd} = params
let opt: any = {deleted: false}
if (timeBegin && !timeEnd) {
opt.createdAt = {$gte: timeBegin};
} else if (timeBegin && timeEnd) {
opt['$and'] = [{createdAt: {$gte: timeBegin}}, {createdAt: {$lte: timeEnd}}];
} else if (!timeBegin && timeEnd) {
opt.createdAt = {$lte: timeEnd};
}
let sort = {_id: -1}
return { opt, sort }
}
}
export const Article = getModelForClass(ArticleClass, { existingConnection: ArticleClass['db'] })