mirror of
https://github.com/purocean/yn.git
synced 2026-09-24 15:46:02 +08:00
feat(core): add ctx.api.rpc method
This commit is contained in:
@@ -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) => {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user