aztec
Version:
Node Js Framework for creating API Services
94 lines (93 loc) • 3.36 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = require("lodash");
const http = require("http");
const fs = require("fs");
const xml = require('xml');
const sendStatus = (data, res) => {
let { status } = data;
if (status) {
res.statusCode = status;
res.statusMessage = http.STATUS_CODES[status];
}
};
exports.extendServerResponse = (svc, res) => {
const extendedValues = {
status: (data) => {
res.statusCode = data;
res.statusMessage = http.STATUS_CODES[data];
return res;
},
send: (data) => {
sendStatus(data, res);
switch (svc.get('format')) {
case 'json':
res.end(JSON.stringify(data));
break;
case 'xml': {
if (lodash_1.isArray(data)) {
let dataAsObject = { collection: {} };
data.forEach((item, i) => {
dataAsObject.collection[i] = item;
});
if (Object.keys(dataAsObject.collection).length === data.length) {
res.write(xml(dataAsObject), 'utf8');
res.end();
break;
}
}
else {
res.write(xml(data), 'utf8');
res.end();
break;
}
}
}
return res;
},
cast: (data) => {
sendStatus(data, res);
switch (svc.get('format')) {
case 'json':
res.write(JSON.stringify(data), 'utf-8');
break;
case 'xml': {
if (lodash_1.isArray(data)) {
let dataAsObject = { collection: {} };
data.forEach((item, i) => {
dataAsObject.collection[i] = item;
});
if (Object.keys(dataAsObject.collection).length === data.length) {
res.write(xml(dataAsObject), 'utf8');
break;
}
}
else {
res.write(xml(data), 'utf8');
break;
}
}
}
return res;
},
render: (path, type = 'html') => {
if (path.indexOf('.') === -1 || path.indexOf(`.${type}`) === -1) {
res.writeHead(200, { 'Content-Type': `text/${type}` });
res.write(fs.readFileSync(`${svc.get('public-path')}/${path}.${type}`, 'utf8'));
return res;
}
else {
if (type === 'js')
type = 'javascript';
res.writeHead(200, { 'Content-Type': `text/${type}` });
res.write(fs.readFileSync(path, 'utf8'));
return res;
}
},
redirect: (path, code = 302) => {
res.writeHead(code, { 'Location': path });
res.end();
}
};
return lodash_1.extend(res, extendedValues);
};