hal-ts
Version:
Package to format api responses into hal format
102 lines • 3.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCollectionResponse = exports.getHalObjectResponse = void 0;
const collection_1 = require("./actions/collection");
const object_1 = require("./actions/object");
/**
* ```
* generateObjectResponse({
* url: "http://localhost:8080/api/user",
* data: { identifier: 1, name: "Zay", isValid: true }
* })
* ```
* @param baseData
* @returns
*/
const getHalObjectResponse = (baseData) => {
const response = Object.assign(Object.assign({ _links: {
self: {
href: `${baseData.url}/${baseData.data.identifier}`,
},
} }, baseData.data), { _embeded: undefined });
if (baseData.data._embeded &&
(0, object_1.isHalEmbededObjectArray)(baseData.data._embeded)) {
response._embeded = baseData.data._embeded
.map((el) => (0, object_1.prepareEmbededData)(el))
.filter((el) => !!el);
}
else if (baseData.data._embeded &&
(0, object_1.isHalEmbededObject)(baseData.data._embeded)) {
response._embeded = (0, object_1.prepareEmbededData)(baseData.data._embeded);
}
return response;
};
exports.getHalObjectResponse = getHalObjectResponse;
/**
* Get a Hal collection response
*
* ```
* const arrayData = [
* {
* url: "http://localhost:8080/api/users",
* data: {
* identifier: 1,
* name: "Marcus",
* isAlive: true,
* _embeded: undefined,
* },
* {
* url: "http://localhost:8080/api/users",
* data: {
* identifier: 2,
* name: "Markus",
* isAlive: false,
* _embeded: undefined,
* },
* }
* {
* url: "http://localhost:8080/api/users",
* data: {
* identifier: 3,
* name: "Marly",
* isAlive: false,
* _embeded: undefined,
* },
* },
* {
* url: "http://localhost:8080/api/users",
* data: {
* identifier: 4,
* name: "Kane",
* isAlive: true,
* _embeded: undefined,
* },
* }
* ]
* const baseData : IHalCollectionRequest = {
* data: arrayData;
* chunk: 2;
* page: 2;
* url: "http://localhost/api/users";
* collectionName: "users";
* }
*
* const response = getCollectionResponse(baseData);
* ```
* @param baseData {@link IHalCollectionRequest}
* @returns collection response in hal format
*/
const getCollectionResponse = (baseData) => {
(0, collection_1.validateCollectionData)(baseData);
const chunks = (0, collection_1.getChunks)(baseData.data, baseData.chunk, baseData.page);
const response = (0, collection_1.generateHalCollectionResponse)({
links: (0, collection_1.prepareCollectionLinks)(baseData.url, baseData.page, baseData.data.length > 0 ? chunks.length : 1, baseData.queryParams),
data: chunks[baseData.page - 1],
total: baseData.data.length || 0,
collectionName: baseData.collectionName,
page: baseData.page,
});
return response;
};
exports.getCollectionResponse = getCollectionResponse;
//# sourceMappingURL=index.js.map