@litert/televoke
Version:
A simple RPC service framework.
102 lines • 3.47 kB
JavaScript
;
/**
* Copyright 2025 Angus.Fenying <fenying@litert.org>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.SimpleJsonApiRouter = void 0;
const Shared = require("../shared");
const Utils_1 = require("../shared/Utils");
const node_events_1 = require("node:events");
class SimpleJsonApiRouter extends node_events_1.EventEmitter {
constructor() {
super(...arguments);
this._apiHandlers = {};
}
get encoding() {
return 'json';
}
registerApi(name, callback) {
this._apiHandlers[name] = callback;
return this;
}
processApi(cb, name, body, ctx) {
if (!this._apiHandlers[name]) {
cb(new Shared.errors.api_not_found({ name }));
return;
}
let args;
try {
args = (0, Utils_1.buffer2json)(body);
}
catch (err) {
cb(new Shared.errors.invalid_packet({ reason: 'invalid_json' }, err));
}
try {
const result = Array.isArray(args) ?
this._apiHandlers[name](ctx, ...args) :
this._apiHandlers[name](ctx, args);
if (result instanceof Promise) {
result.then((data) => {
try {
cb(JSON.stringify(data ?? null));
}
catch (e) {
this._processError(cb, e, name);
}
}, (e) => { this._processError(cb, e, name); });
}
else {
cb(JSON.stringify(result ?? null));
}
}
catch (e) {
this._processError(cb, e, name);
}
}
_processError(cb, e, name) {
if (e instanceof Shared.TelevokeError) {
cb(e);
return;
}
if (e instanceof Shared.TvErrorResponse) {
cb(new Shared.errors.app_error(JSON.stringify(e.data ?? null)));
return;
}
cb(new Shared.errors.server_internal_error());
this.emit('error', new Shared.errors.unprocessable_error({ api: name }, e));
}
processLegacyApi(cb, name, args, ctx) {
if (!this._apiHandlers[name]) {
cb(new Shared.errors.api_not_found({ name }));
return;
}
try {
const result = Array.isArray(args) ?
this._apiHandlers[name](ctx, ...args) :
this._apiHandlers[name](ctx, args);
if (result instanceof Promise) {
result.then((data) => { cb(data ?? null); }, (e) => { this._processError(cb, e, name); });
}
else {
cb(result ?? null);
}
}
catch (e) {
this._processError(cb, e, name);
}
}
}
exports.SimpleJsonApiRouter = SimpleJsonApiRouter;
//# sourceMappingURL=SimpleJsonApiRouter.js.map