Skip to content

Commit fcf81f8

Browse files
committed
Optimize API execution
1 parent 1d322be commit fcf81f8

File tree

2 files changed

+20
-21
lines changed

2 files changed

+20
-21
lines changed

lib/application.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ class Application extends events.EventEmitter {
6363

6464
runScript(methodName, sandbox = this.sandbox) {
6565
const script = this.api.get(methodName);
66-
if (!script) throw new Error('Not found');
66+
if (!script) return null;
6767
return script.runInContext(sandbox, SCRIPT_OPTIONS);
6868
}
6969

lib/server.js

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -81,44 +81,43 @@ class Client {
8181
res.end(result);
8282
}
8383

84-
async execute(method, args) {
85-
const { application } = this;
84+
async rpc(method, args) {
85+
const { application, res, connection } = this;
8686
const { semaphore } = application.server;
87-
await semaphore.enter();
87+
try {
88+
await semaphore.enter();
89+
} catch {
90+
this.error(504);
91+
return;
92+
}
8893
try {
8994
const session = await application.auth.restore(this);
9095
const sandbox = session ? session.sandbox : undefined;
9196
const context = session ? session.context : {};
9297
const exp = application.runScript(method, sandbox);
98+
if (!exp) {
99+
this.error(404);
100+
return;
101+
}
93102
const proc = exp(context);
94103
if (!session && proc.access !== 'public') {
95-
semaphore.leave();
96-
throw new Error(`Forbidden: /api/${method}`);
104+
this.error(403, new Error(`Forbidden: /api/${method}`));
105+
return;
97106
}
98107
const result = await proc.method(args);
99108
if (!session && proc.access === 'public') {
100109
const session = application.auth.start(this, result.userId);
101110
result.token = session.token;
102111
}
103-
return JSON.stringify(result);
112+
const data = JSON.stringify(result);
113+
if (connection) connection.send(data);
114+
else res.end(data);
115+
} catch (err) {
116+
this.error(500, err);
104117
} finally {
105118
semaphore.leave();
106119
}
107120
}
108-
109-
async rpc(method, args) {
110-
const { res, connection } = this;
111-
try {
112-
const result = await this.execute(method, args);
113-
if (connection) connection.send(result);
114-
else res.end(result);
115-
} catch (err) {
116-
if (err.message === 'Not found') this.error(404);
117-
else if (err.message === 'Semaphore timeout') this.error(504);
118-
else if (err.message.startsWith('Forbidden:')) this.error(403, err);
119-
else this.error(500, err);
120-
}
121-
}
122121
}
123122

124123
const listener = application => (req, res) => {

0 commit comments

Comments
 (0)