fix: page macor

This commit is contained in:
Innei
2022-04-22 11:51:53 +08:00
parent fac86ab60b
commit 22c9730efc
3 changed files with 42 additions and 15 deletions

View File

@@ -4,9 +4,11 @@ import slugify from 'slugify'
import { Injectable } from '@nestjs/common'
import { CannotFindException } from '~/common/exceptions/cant-find.exception'
import { BusinessEvents, EventScope } from '~/constants/business-event.constant'
import { EventManagerService } from '~/processors/helper/helper.event.service'
import { ImageService } from '~/processors/helper/helper.image.service'
import { TextMacroService } from '~/processors/helper/helper.macro.service'
import { InjectModel } from '~/transformers/model.transformer'
import { PageModel } from './page.model'
@@ -18,6 +20,7 @@ export class PageService {
private readonly pageModel: MongooseModel<PageModel>,
private readonly imageService: ImageService,
private readonly eventManager: EventManagerService,
private readonly macroService: TextMacroService,
) {}
public get model() {
@@ -46,17 +49,33 @@ export class PageService {
doc.slug = slugify(doc.slug)
}
await this.model.updateOne(
{ _id: id },
{ ...omit(doc, PageModel.protectedKeys) },
)
const newDoc = await this.model
.findOneAndUpdate(
{ _id: id },
{ ...omit(doc, PageModel.protectedKeys) },
{ new: true },
)
.lean()
if (!newDoc) {
throw new CannotFindException()
}
process.nextTick(async () => {
await Promise.all([
this.imageService.recordImageDimensions(this.pageModel, id),
this.pageModel.findById(id).then((doc) =>
this.eventManager.broadcast(BusinessEvents.PAGE_UPDATED, doc, {
scope: EventScope.TO_SYSTEM_VISITOR,
}),
this.eventManager.broadcast(BusinessEvents.PAGE_UPDATED, newDoc, {
scope: EventScope.TO_SYSTEM,
}),
this.eventManager.broadcast(
BusinessEvents.PAGE_UPDATED,
{
...newDoc,
text: this.macroService.replaceTextMacro(newDoc.text, newDoc),
},
{
scope: EventScope.TO_VISITOR,
},
),
])
})

View File

@@ -102,13 +102,20 @@ export class TextMacroService {
{},
)
// TODO catch error
return safeEval(`return ${functions}`, {
dayjs: deepCloneWithFunction(dayjs),
fromNow: (time: Date | string) => dayjs(time).fromNow(),
try {
return safeEval(
`return ${functions}`,
{
dayjs: deepCloneWithFunction(dayjs),
fromNow: (time: Date | string) => dayjs(time).fromNow(),
...variables,
})
...variables,
},
{ timeout: 1000 },
)
} catch {
return match
}
}
})
}

View File

@@ -1,6 +1,6 @@
import vm2 from 'vm2'
export function safeEval(code: string, context = {}) {
export function safeEval(code: string, context = {}, options?: vm2.VMOptions) {
const sandbox = {
global: {},
}
@@ -17,6 +17,7 @@ export function safeEval(code: string, context = {}) {
sandbox,
eval: false,
...options,
})
return VM.run(code)