fix: test error

This commit is contained in:
Innei
2022-03-23 00:26:04 +08:00
parent 201afc92e1
commit 812f94e254
4 changed files with 35 additions and 6 deletions

View File

@@ -12,7 +12,6 @@ import {
import { Interval } from '@nestjs/schedule'
import { isURL } from 'class-validator'
import { cloneDeep } from 'lodash'
import xss from 'xss'
import PKG from '../../../package.json'
import { SnippetModel } from '../snippet/snippet.model'
import {
@@ -191,9 +190,13 @@ export class ServerlessService {
}
return await safeEval(
`${await this.convertTypescriptCode(
`async function func() {
${await this.convertTypescriptCode(
functionString,
)}; return handler(context, require)`,
)}; return handler(context, require)
}
return func()
`,
{
...globalContext,
global: globalContext,

View File

@@ -4,7 +4,7 @@ export function safeEval(code: string, context = {}) {
global: {},
}
code = `((async () => { ${code} })())`
code = `((() => { ${code} })())`
if (context) {
Object.keys(context).forEach((key) => {
sandbox[key] = context[key]

View File

@@ -140,4 +140,30 @@ describe('test serverless function service', () => {
).rejects.toThrow()
})
})
test('case-7: esm default import', async () => {
const model = new SnippetModel()
Object.assign<SnippetModel, Partial<SnippetModel>>(model, {
type: SnippetType.Function,
raw: `import axios from 'axios';async function handler(context, require) { return axios }`,
})
const data = await service.injectContextIntoServerlessFunctionAndCall(
model,
{ req: {} as any, res: {} as any },
)
expect(typeof data.get).toBe('function')
})
test('case-7: esm named import', async () => {
const model = new SnippetModel()
Object.assign<SnippetModel, Partial<SnippetModel>>(model, {
type: SnippetType.Function,
raw: `import {get} from 'axios';async function handler(context, require) { return get }`,
})
const data = await service.injectContextIntoServerlessFunctionAndCall(
model,
{ req: {} as any, res: {} as any },
)
expect(typeof data).toBe('function')
})
})

View File

@@ -1,6 +1,6 @@
import { safeEval } from '~/utils/safe-eval.util'
describe.only('test safe-eval', () => {
describe('test safe-eval', () => {
it('should eval', () => {
const res = safeEval(`return 1 + 2`)
expect(res).toBe(3)