Browse Source

Add error handling

Check if service can initialize data source before making requests.
master
TheoryOfNekomata 8 months ago
parent
commit
284a5cd3bf
1 changed files with 35 additions and 22 deletions
  1. +35
    -22
      src/handlers.ts

+ 35
- 22
src/handlers.ts View File

@@ -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;


Loading…
Cancel
Save