@darlean/webservices
Version:
Library for building actor-based webservices via the Darlean Web Gateways service
47 lines (46 loc) • 1.75 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonResponseEncoder = exports.JsonRequestParser = void 0;
const jtd_1 = __importDefault(require("ajv/dist/jtd"));
const wrapper_1 = require("./wrapper");
class JsonRequestParser {
constructor(schema) {
const a = new jtd_1.default();
this.parser = a.compileParser(schema);
}
async parse(request) {
if (!(request instanceof wrapper_1.WebRequest)) {
request = wrapper_1.WebRequest.from(request);
}
// This call is async because for long body, we may have to perform
// async calls to webserver in the future to fetch next chunk
const text = request.getTextBody();
if (text) {
const parsed = this.parser(text);
if (!parsed) {
throw new Error(`JSON validation error: ${this.parser.message} at ${this.parser.position}`);
}
return parsed;
}
else {
throw new Error('No request body');
}
}
}
exports.JsonRequestParser = JsonRequestParser;
class JsonResponseEncoder {
constructor(schema) {
const a = new jtd_1.default();
this.serializer = a.compileSerializer(schema);
}
async pushAndEnd(value, response) {
response.setHeader('content-type', 'application/json');
const text = this.serializer(value);
await response.push(Buffer.from(text, 'utf-8'));
return await response.end();
}
}
exports.JsonResponseEncoder = JsonResponseEncoder;