diff --git a/src/handlers.ts b/src/handlers.ts index 00e8281..b9ca157 100644 --- a/src/handlers.ts +++ b/src/handlers.ts @@ -138,15 +138,20 @@ export const handleGetCollection: Middleware = ({ }; } - await theResource.dataSource.initialize(); - const resData = await theResource.dataSource.getMultiple(); // TODO paginated responses per resource - const theFormatted = theSerializerPair.serialize(resData); + try { + await theResource.dataSource.initialize(); + const resData = await theResource.dataSource.getMultiple(); // TODO paginated responses per resource + const theFormatted = theSerializerPair.serialize(resData); - res.writeHead(constants.HTTP_STATUS_OK, { - 'Content-Type': theMediaType, - 'X-Resource-Total-Item-Count': resData.length - }); - res.end(theFormatted); + res.writeHead(constants.HTTP_STATUS_OK, { + 'Content-Type': theMediaType, + 'X-Resource-Total-Item-Count': resData.length + }); + res.end(theFormatted); + } catch { + res.statusCode = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; + res.end(); + } return { handled: true @@ -201,23 +206,31 @@ export const handleGetItem: Middleware = ({ }; } - await theResource.dataSource.initialize(); - const singleResDatum = await theResource.dataSource.getSingle(mainResourceId); - if (singleResDatum) { - const theFormatted = theSerializerPair.serialize(singleResDatum); - res.writeHead(constants.HTTP_STATUS_OK, { 'Content-Type': theMediaType }); - res.end(theFormatted); + try { + await theResource.dataSource.initialize(); + const singleResDatum = await theResource.dataSource.getSingle(mainResourceId); + if (singleResDatum) { + const theFormatted = theSerializerPair.serialize(singleResDatum); + res.writeHead(constants.HTTP_STATUS_OK, {'Content-Type': theMediaType}); + res.end(theFormatted); + return { + handled: true + }; + } + + res.statusCode = constants.HTTP_STATUS_NOT_FOUND; + res.statusMessage = `${theResource.itemName} Not Found`; + res.end(); + return { + handled: true + }; + } catch { + res.statusCode = constants.HTTP_STATUS_INTERNAL_SERVER_ERROR; + res.end(); return { handled: true }; } - - res.statusCode = constants.HTTP_STATUS_NOT_FOUND; - res.statusMessage = `${theResource.itemName} Not Found`; - res.end(); - return { - handled: true - }; }; @@ -271,8 +284,8 @@ export const handleDeleteItem: Middleware = ({ } } - await theResource.dataSource.initialize(); try { + await theResource.dataSource.initialize(); const response = await theResource.dataSource.delete(mainResourceId); if (typeof response !== 'undefined' && !response && theResource.throws404OnDeletingNotFound) { res.statusCode = constants.HTTP_STATUS_NOT_FOUND;