Skip to content

Commit

Permalink
feat: add logger in FHIRAPI and refactor resFunc
Browse files Browse the repository at this point in the history
- extract resFunc to global variable
- add warn logger
  • Loading branch information
Chinlinlee committed Mar 2, 2022
1 parent ce60bf2 commit bff8643
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 75 deletions.
10 changes: 8 additions & 2 deletions api/FHIRApiService/condition-delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ const {
const FHIR = require('../../models/FHIR/fhir/fhir').Fhir;
const { isRealObject } = require('../apiService');
const user = require('../APIservices/user.service');
const { logger } = require('../../utils/log');
const path = require('path');
const PWD_FILENAME = path.relative(process.cwd(), __filename);

/**
*
Expand All @@ -16,6 +19,7 @@ const user = require('../APIservices/user.service');
* @returns
*/
module.exports = async function(req, res, resourceType, paramsSearch) {
logger.info(`[Info: do condition-delete] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}] [Content-Type: ${res.getHeader("content-type")}] [Url-SearchParam: ${req.url}] `);
let doRes = function (code , item) {
if (res.getHeader("content-type").includes("xml")) {
let fhir = new FHIR();
Expand All @@ -25,6 +29,7 @@ module.exports = async function(req, res, resourceType, paramsSearch) {
return res.status(code).send(item);
};
if (!await user.checkTokenPermission(req, resourceType, "delete")) {
logger.warn(`[Warn: Request token doesn't have permission with this API] [From-File: ${PWD_FILENAME}] [From-IP: ${req.socket.remoteAddress}]`);
return doRes(403,handleError.forbidden("Your token doesn't have permission with this API"));
}
let queryParameter = _.cloneDeep(req.query);
Expand All @@ -45,7 +50,7 @@ module.exports = async function(req, res, resourceType, paramsSearch) {
paramsSearch[key](queryParameter);
} catch (e) {
if (key != "$and") {
console.error(e);
logger.error(`[Error: Unknown search parameter ${key} or value ${queryParameter[key]}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}] [${e}]`);
return doRes(400 , handleError.processing(`Unknown search parameter ${key} or value ${queryParameter[key]}`));
}
}
Expand All @@ -59,7 +64,8 @@ module.exports = async function(req, res, resourceType, paramsSearch) {
let info = handleError.informational(`delete successfully, deleted count : ${deletion.deletedCount}`);
return doRes(200 , info);
} catch (e) {
console.log(`api ${process.env.FHIRSERVER_APIPATH}/${resourceType}/ has error, `, e);
let errorStr = JSON.stringify(e, Object.getOwnPropertyNames(e));
logger.error(`[Error: ${errorStr}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
let operationOutcomeError = handleError.exception(e);
return doRes(500 , operationOutcomeError);
}
Expand Down
105 changes: 66 additions & 39 deletions api/FHIRApiService/create.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,72 @@ const { checkReference, getNotExistReferenceList } = require('../apiService');
const FHIR = require('../../models/FHIR/fhir/fhir').Fhir;
const user = require('../APIservices/user.service');
const validateContained = require('./validateContained');
const { logger } = require('../../utils/log');
const path = require('path');
const PWD_FILENAME = path.relative(process.cwd(), __filename);

const responseFunc = {
/**
*
* @param {Object} doc
* @param {import('express').Request} req express request
* @param {import('express').Response} res express response
* @param {string} resourceType resource type
* @param {function} doResCallback callback function
* @returns
*/
"true": (doc, req, res, resourceType, doResCallback) => {
let reqBaseUrl = `${req.protocol}://${req.get('host')}/`;
let fullAbsoluteUrl = new URL(req.originalUrl, reqBaseUrl).href;
res.set("Location", fullAbsoluteUrl);
res.append("Last-Modified", (new Date()).toUTCString());
logger.info(`[Info: create id: ${doc.id} successfully] [Resource Type: ${resourceType}] [From-file: ${PWD_FILENAME}]`);
return doResCallback(201 , doc);
},
/**
*
* @param {Object} err
* @param {import('express').Request} req express request
* @param {import('express').Response} res express response
* @param {string} resourceType resource type
* @param {function} doResCallback callback function
* @returns
*/
"false": (err, req, res, resourceType, doResCallback) => {
let operationOutcomeMessage;
if (err.message.code == 11000) {
operationOutcomeMessage = {
code : 409 ,
msg : handleError.duplicate(err.message)
};
} else if (err.stack.includes("ValidationError")) {
operationOutcomeMessage = {
code : 400 ,
msg : handleError.processing(err.message)
};
} else if (err.stack.includes("stored by resource")) {
operationOutcomeMessage = {
code : 400 ,
msg : handleError.processing(err.message)
};
} else {
operationOutcomeMessage = {
code : 500 ,
msg : handleError.exception(err.message)
};
}
logger.error(`[Error: ${JSON.stringify(operationOutcomeMessage)}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
return doResCallback(operationOutcomeMessage.code , operationOutcomeMessage.msg);
}
};
/**
* @param {import("express").Request} req
* @param {import("express").Response} res
* @param {String} resourceType
* @returns
*/
module.exports = async function(req, res , resourceType) {
logger.info(`[Info: do create] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}] [Content-Type: ${res.getHeader("content-type")}]`);
let doRes = function (code , item) {
if (res.getHeader("content-type").includes("xml")) {
let fhir = new FHIR();
Expand All @@ -25,45 +83,10 @@ module.exports = async function(req, res , resourceType) {
return res.status(code).send(item);
};
if (!await user.checkTokenPermission(req, resourceType, "create")) {
logger.warn(`[Warn: Request token doesn't have permission with this API] [From-File: ${PWD_FILENAME}] [From-IP: ${req.socket.remoteAddress}]`);
return doRes(403,handleError.forbidden("Your token doesn't have permission with this API"));
}
console.log(`doPost-create ${resourceType}`);
try {
let resFunc = {
"true": (doc) => {
let reqBaseUrl = `${req.protocol}://${req.get('host')}/`;
let fullAbsoluteUrl = new URL(req.originalUrl, reqBaseUrl).href;
res.set("Location", fullAbsoluteUrl);
res.append("Last-Modified", (new Date()).toUTCString());
console.log(`create ${resourceType} id: ${doc.id} successfully`);
return doRes(201 , doc);
},
"false": (err) => {
let operationOutcomeMessage;
if (err.message.code == 11000) {
operationOutcomeMessage = {
code : 409 ,
msg : handleError.duplicate(err.message)
};
} else if (err.stack.includes("ValidationError")) {
operationOutcomeMessage = {
code : 400 ,
msg : handleError.processing(err.message)
};
} else if (err.stack.includes("stored by resource")) {
operationOutcomeMessage = {
code : 400 ,
msg : handleError.processing(err.message)
};
} else {
operationOutcomeMessage = {
code : 500 ,
msg : handleError.exception(err.message)
};
}
return doRes(operationOutcomeMessage.code , operationOutcomeMessage.msg);
}
};
let insertData = req.body;
if (_.get(insertData, "contained")) {
let containedResources = _.get(insertData, "contained");
Expand All @@ -72,6 +95,7 @@ module.exports = async function(req, res , resourceType) {
let validation = await validateContained(resource, index);
if (!validation.status) {
let operationOutcomeError = handleError.processing(`The resource in contained error. ${validation.message}`);
logger.error(`[Error: ${JSON.stringify(operationOutcomeError)}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
return doRes(400, operationOutcomeError);
}
}
Expand All @@ -82,13 +106,15 @@ module.exports = async function(req, res , resourceType) {
let notExistReferenceList = getNotExistReferenceList(checkReferenceRes);
let operationOutcomeError = handleError.processing(`The reference not found : ${_.map(notExistReferenceList , "value").join(",")}`);
_.set(operationOutcomeError , "issue.0.location" , _.map(notExistReferenceList , "path"));
logger.error(`[Error: ${JSON.stringify(operationOutcomeError)}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
return doRes(400, operationOutcomeError);
}
}
let [status, doc] = await doInsertData(insertData, resourceType);
return resFunc[status](doc);
return responseFunc[status](doc, req, res, resourceType, doRes);
} catch (e) {
console.error(e);
let errorStr = JSON.stringify(e, Object.getOwnPropertyNames(e));
logger.error(`[Error: ${errorStr})}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
let operationOutcomeError = handleError.exception(e);
return doRes(500 , operationOutcomeError);
}
Expand All @@ -103,7 +129,8 @@ async function doInsertData(insertData , resourceType) {
let doc = await insertDataObject.save();
return [true, doc.getFHIRField()];
} catch (e) {
console.error(e);
let errorStr = JSON.stringify(e, Object.getOwnPropertyNames(e));
logger.error(`[Error: ${errorStr}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
return [false , e];
}
}
70 changes: 48 additions & 22 deletions api/FHIRApiService/delete.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,57 @@ const {
const _ = require('lodash');
const FHIR = require('../../models/FHIR/fhir/fhir').Fhir;
const user = require('../APIservices/user.service');
const { logger } = require('../../utils/log');
const path = require('path');
const PWD_FILENAME = path.relative(process.cwd(), __filename);

const responseFunc = {
/**
*
* @param {Object} doc
* @param {import('express').Request} req express request
* @param {import('express').Response} res express response
* @param {string} resourceType resource type
* @param {function} doResCallback callback function
* @returns
*/
"true": (doc, req, res, resourceType, doCallback) => {
if (!doc) {
let errorMessage = `not found ${resourceType}/${req.params.id}`;
logger.warn(`[Warn: ${errorMessage}] [Resource-Type: ${resourceType}]`);
return doCallback(404, handleError["not-found"](errorMessage));
}
return doCallback(200, getDeleteMessage(resourceType, req.params.id));
},
/**
*
* @param {Object} err
* @param {import('express').Request} req express request
* @param {import('express').Response} res express response
* @param {string} resourceType resource type
* @param {function} doResCallback callback function
* @returns
*/
"false": (err, req, res, resourceType, doCallback) => {
if (_.isString(err)) {
if (err.includes("not found")) {
return doCallback(404, handleError['not-found'](err));
}
return doCallback(500, handleError.exception(err));
}
return doCallback(500, handleError.exception(err.message));
}
};

/**
* @param {import("express").Request} req
* @param {import("express").Response} res
* @param {String} resourceType
* @returns
*/
module.exports = async function(req, res, resourceType) {
let doRes = function (code , item) {
module.exports = async function (req, res, resourceType) {
logger.info(`[Info: do delete by id, id: ${req.params.id}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}] [Content-Type: ${res.getHeader("content-type")}]`);
let doRes = function (code, item) {
if (res.getHeader("content-type").includes("xml")) {
let fhir = new FHIR();
let xmlItem = fhir.objToXml(item);
Expand All @@ -23,28 +65,11 @@ module.exports = async function(req, res, resourceType) {
return res.status(code).send(item);
};
if (!await user.checkTokenPermission(req, resourceType, "delete")) {
logger.warn(`[Warn: Request token doesn't have permission with this API] [From-File: ${PWD_FILENAME}] [From-IP: ${req.socket.remoteAddress}]`);
return doRes(403,handleError.forbidden("Your token doesn't have permission with this API"));
}
let resFunc = {
"true": (doc) => {
if (!doc) {
let errorMessage = `not found ${resourceType}/${req.params.id}`;
return doRes(404,handleError["not-found"](errorMessage));
}
return doRes(200,getDeleteMessage(resourceType, req.params.id));
},
"false": (err) => {
if (_.isString(err)) {
if (err.includes("not found")) {
return doRes(404, handleError['not-found'](err));
}
return doRes(500,handleError.exception(err));
}
return doRes(500,handleError.exception(err.message));
}
};
let [status, doc] = await doDeleteData(req, resourceType);
return resFunc[status.toString()](doc);
return responseFunc[status.toString()](doc, req, res, resourceType, doRes);
};

async function doDeleteData(req, resourceType) {
Expand All @@ -54,7 +79,8 @@ async function doDeleteData(req, resourceType) {
id: id
}, (err, doc) => {
if (err) {
console.error(err);
let errorStr = JSON.stringify(err, Object.getOwnPropertyNames(err));
logger.error(`[Error ${errorStr}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
return resolve([false, err]);
}
return resolve([true, doc]);
Expand Down
9 changes: 7 additions & 2 deletions api/FHIRApiService/history.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ const {
const FHIR = require('../../models/FHIR/fhir/fhir').Fhir;
const { handleError } = require('../../models/FHIR/httpMessage');
const user = require('../APIservices/user.service');
const { logger } = require('../../utils/log');
const path = require('path');
const PWD_FILENAME = path.relative(process.cwd(), __filename);

/**
* @param {import("express").Request} req
Expand All @@ -14,6 +17,7 @@ const user = require('../APIservices/user.service');
* @returns
*/
module.exports = async function(req, res, resourceType) {
logger.info(`[Info: do history-instance by id, id: ${req.params.id}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}] [Content-Type: ${res.getHeader("content-type")}] [Url-SearchParam: ${req.url}] `);
let doRes = function (code , item) {
if (res.getHeader("content-type").includes("xml")) {
let fhir = new FHIR();
Expand All @@ -23,6 +27,7 @@ module.exports = async function(req, res, resourceType) {
return res.status(code).send(item);
};
if (!await user.checkTokenPermission(req, resourceType, "history")) {
logger.warn(`[Warn: Request token doesn't have permission with this API] [From-File: ${PWD_FILENAME}] [From-IP: ${req.socket.remoteAddress}]`);
return doRes(403,handleError.forbidden("Your token doesn't have permission with this API"));
}
let queryParameter = _.cloneDeep(req.query);
Expand All @@ -31,7 +36,6 @@ module.exports = async function(req, res, resourceType) {
let paginationLimit = queryParameter['_count'] == undefined ? 100 : queryParameter['_count'];
_.set(req.query, "_offset", paginationSkip);
_.set(req.query, "_count", paginationLimit);
let realLimit = paginationLimit + paginationSkip;
delete queryParameter['_count'];
delete queryParameter['_offset'];
try {
Expand Down Expand Up @@ -60,7 +64,8 @@ module.exports = async function(req, res, resourceType) {
res.header('Last-Modified', new Date().toUTCString());
return doRes(200, bundle);
} catch (e) {
console.log(`api ${process.env.FHIRSERVER_APIPATH}/${resourceType}/:id/history has error, `, e);
let errorStr = JSON.stringify(e, Object.getOwnPropertyNames(e));
logger.error(`[Error: ${errorStr})}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
let operationOutcomeError = handleError.exception(e);
return doRes(500, operationOutcomeError);
}
Expand Down
9 changes: 8 additions & 1 deletion api/FHIRApiService/read.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ const {
} = require('../../models/FHIR/httpMessage');
const FHIR = require('../../models/FHIR/fhir/fhir').Fhir;
const user = require('../APIservices/user.service');
const { logger } = require('../../utils/log');
const path = require('path');
const PWD_FILENAME = path.relative(process.cwd(), __filename);

/**
* @param {import("express").Request} req
Expand All @@ -12,6 +15,7 @@ const user = require('../APIservices/user.service');
* @returns
*/
module.exports = async function (req , res , resourceType) {
logger.info(`[Info: do create] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}] [Content-Type: ${res.getHeader("content-type")}]`);
let doRes = function (code, item) {
if (res.getHeader("content-type").includes("xml")) {
let fhir = new FHIR();
Expand All @@ -21,6 +25,7 @@ module.exports = async function (req , res , resourceType) {
return res.status(code).send(item);
};
if (!await user.checkTokenPermission(req, resourceType, "read")) {
logger.warn(`[Warn: Request token doesn't have permission with this API] [From-File: ${PWD_FILENAME}] [From-IP: ${req.socket.remoteAddress}]`);
return doRes(403,handleError.forbidden("Your token doesn't have permission with this API"));
}
let id = req.params.id;
Expand All @@ -34,10 +39,12 @@ module.exports = async function (req , res , resourceType) {
return doRes(200, responseDoc);
}
let errorMessage = `not found ${resourceType}/${id}`;
logger.warn(`[Warn: ${errorMessage}] [Resource-Type: ${resourceType}]`);
let operationOutcomeError = handleError.exception(errorMessage);
return doRes(404, operationOutcomeError);
} catch (e) {
console.log(`api ${process.env.FHIRSERVER_APIPATH}/${resourceType}/:id has error, `, e);
let errorStr = JSON.stringify(e, Object.getOwnPropertyNames(e));
logger.error(`[Error: ${errorStr}] [Resource Type: ${resourceType}] [From-File: ${PWD_FILENAME}]`);
let operationOutcomeError = handleError.exception(e);
return doRes(500, operationOutcomeError);
}
Expand Down
Loading

0 comments on commit bff8643

Please sign in to comment.