From e020f1146b6dbfa64534a805a3ac0f35d4e03044 Mon Sep 17 00:00:00 2001 From: purocean Date: Mon, 22 Nov 2021 11:56:53 +0800 Subject: [PATCH] feat(core): add `ctx.api.rpc` method --- src/main/server/index.ts | 15 +++++++++++++++ src/renderer/support/api.ts | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/main/server/index.ts b/src/main/server/index.ts index 4ed92d43..8a5f6c51 100644 --- a/src/main/server/index.ts +++ b/src/main/server/index.ts @@ -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) => { diff --git a/src/renderer/support/api.ts b/src/renderer/support/api.ts index 48098f70..a4cdd676 100644 --- a/src/renderer/support/api.ts +++ b/src/renderer/support/api.ts @@ -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 +}