feat(core): add ctx.api.rpc method

This commit is contained in:
purocean
2021-11-22 11:56:53 +08:00
parent 8b65ba4483
commit e020f1146b
2 changed files with 34 additions and 0 deletions
+15
View File
@@ -279,6 +279,20 @@ const choose = async (ctx: any, next: any) => {
}
}
const rpc = async (ctx: any, next: any) => {
if (ctx.path.startsWith('/api/rpc') && ctx.method === 'POST') {
const { code } = ctx.request.body
const AsyncFunction = Object.getPrototypeOf(async () => 0).constructor
const fn = new AsyncFunction('require', code)
const nodeRequire = (id: string) => id.startsWith('.')
? require(path.resolve(__dirname, '..', id))
: require(id)
ctx.body = result('ok', 'success', await fn(nodeRequire))
} else {
await next()
}
}
const wrapper = async (ctx: any, next: any, fun: any) => {
try {
await fun(ctx, next)
@@ -316,6 +330,7 @@ const server = (port = 3000) => {
app.use(async (ctx: any, next: any) => await wrapper(ctx, next, setting))
app.use(async (ctx: any, next: any) => await wrapper(ctx, next, choose))
app.use(async (ctx: any, next: any) => await wrapper(ctx, next, tmpFile))
app.use(async (ctx: any, next: any) => await wrapper(ctx, next, rpc))
// static file
app.use(async (ctx: any, next: any) => {
+19
View File
@@ -333,3 +333,22 @@ export async function runCode (language: string, code: string, callback?: { name
return data
}
/**
* Eval cade on Electron main process
*
* await ctx.api.rpc('return 1 + 1') // result 2
* await ctx.api.rpc(`return require('os').platform()`) // result 'darwin'
* await ctx.api.rpc(`return require('./constant').APP_NAME`) // result 'yank-note'
*
* @param code Function body
*/
export async function rpc (code: string) {
const { data } = await fetchHttp('/api/rpc', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
})
return data
}