@crowdin/app-project-module
Version:
Module that generates for you all common endpoints for serving standalone Crowdin App
64 lines (63 loc) • 2.95 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = require("../../util");
const logger_1 = require("../../util/logger");
const BUFFERING_FLAG = '~buffering~';
function handle(module, canHandleStream = false) {
return (0, util_1.runAsyncWrapper)((req, res) => __awaiter(this, void 0, void 0, function* () {
try {
if (canHandleStream && req.headers['transfer-encoding'] === 'chunked') {
if (!('processStream' in module)) {
res.writeHead(202, {}).end();
return;
}
res.writeHead(200, {
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream',
'X-Accel-Buffering': 'no',
});
req.on('data', (chunk) => __awaiter(this, void 0, void 0, function* () {
let chunkStr = chunk.toString();
// actually we checked if processStream exists already, but need do to this again to calm down TS compiler
chunkStr = module.processStream
? yield module.processStream(chunkStr, req.query, req.crowdinApiClient, req.crowdinContext)
: chunkStr;
if (!chunkStr && typeof chunkStr !== 'string') {
res.write(BUFFERING_FLAG);
return;
}
res.write(chunkStr);
}));
req.on('end', () => {
res.end();
});
req.on('error', (e) => {
if (req.logError) {
req.logError(e);
}
res.end();
});
return;
}
const result = yield module.processRequest(req.body, req.query, req.crowdinApiClient, req.crowdinContext);
res.send(result);
}
catch (e) {
if (req.logError) {
req.logError(e);
}
res.send({ error: { message: (0, logger_1.getErrorMessage)(e) } });
}
}));
}
exports.default = handle;