From 381cc98ec202df1947d8ef93f6a078ca7d103415 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Dewitte?= Date: Wed, 19 Apr 2023 22:59:48 +0200 Subject: [PATCH] exports in `hal` to build an HalState from scatch --- src/state/hal.ts | 4 +-- test/unit/state/hal.ts | 74 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 74 insertions(+), 4 deletions(-) diff --git a/src/state/hal.ts b/src/state/hal.ts index 28a1939..e9548c9 100644 --- a/src/state/hal.ts +++ b/src/state/hal.ts @@ -22,7 +22,7 @@ export class HalState extends BaseState { } - private serializeLinks(): hal.HalResource['_links'] { + serializeLinks(): hal.HalResource['_links'] { const links: hal.HalResource['_links'] = { self: { href: this.uri }, @@ -113,7 +113,7 @@ export const factory:StateFactory = async (client, uri, response): Promise { @@ -229,6 +230,75 @@ describe('HAL state factory', () => { happy: 2020, }); + }); + it('should correctly build HALState from scratch', async() => { + + const hal = await callFactory({ + _links: { + self: { + href: '/foo', + }, + author: { + href: 'https://evertpot.com/', + }, + foo: [ + { + href: '/bar', + }, + { + href: '/bar2', + }, + { + href: '/bar3', + }, + ] + }, + happy: 2020, + }) as HalState; + + // More direct way to get a json + const json : HalResource = { + _links: hal.serializeLinks(), + ...hal.data + }; + // Building an HalState + const { + _links, + ...newBody + } = json; + const context = json._links.self.href; + const links = new Links(context, parseHalLinks(context, json)); + const hal2 = new HalState({ + client: hal.client, + uri: context, + data: newBody, + headers: new Headers(), + links, + }); + expect(JSON.parse(hal2.serializeBody())).to.eql({ + _links: { + self: { + href: 'http://example/', + }, + author: { + href: 'https://evertpot.com/', + }, + foo: [ + { + href: '/bar', + }, + { + href: '/bar2', + }, + { + href: '/bar3', + }, + ] + }, + happy: 2020, + }); + + }); it('should handle JSON documents that are arrays', async () => {