From 2ec2022dced94ae75471598ea72a2d9c63c6a3a9 Mon Sep 17 00:00:00 2001 From: Lars Vierbergen Date: Tue, 5 Nov 2024 08:31:51 +0100 Subject: [PATCH] [ACC-1682] Add HalFormsTemplateBuilder#fromTemplate method Add ability to easily create a builder from an existing hal forms template, to modify the template when it's necessary --- packages/hal-forms/__tests__/builder.ts | 16 ++++++++++++++++ packages/hal-forms/src/builder.ts | 12 ++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 packages/hal-forms/__tests__/builder.ts diff --git a/packages/hal-forms/__tests__/builder.ts b/packages/hal-forms/__tests__/builder.ts new file mode 100644 index 0000000..3953ed2 --- /dev/null +++ b/packages/hal-forms/__tests__/builder.ts @@ -0,0 +1,16 @@ +import buildTemplate, { HalFormsTemplateBuilder } from "../src/builder"; + +describe("HalFormsTemplateBuilder", () => { + it("#fromTemplate", () => { + const original = buildTemplate("GET", "/") + .withContentType("application/json") + .addProperty("xyz", p => p.withPrompt("Test")); + + const fromTemplate = HalFormsTemplateBuilder.fromTemplate(original); + + expect(fromTemplate.contentType).toEqual("application/json"); + expect(fromTemplate.properties).toHaveLength(1); + expect(fromTemplate.properties[0]?.name).toEqual("xyz"); + expect(fromTemplate.properties[0]?.prompt).toEqual("Test"); + }) +}); diff --git a/packages/hal-forms/src/builder.ts b/packages/hal-forms/src/builder.ts index 92859fc..2edaef6 100644 --- a/packages/hal-forms/src/builder.ts +++ b/packages/hal-forms/src/builder.ts @@ -19,6 +19,18 @@ export class HalFormsTemplateBuilder implements HalFormsTemplate return new HalFormsTemplateBuilder(request.method + " "+request.url, request); } + public static fromTemplate(template: HalFormsTemplate>): HalFormsTemplateBuilder { + let builder = this.from(template.request) + .withName(template.name) + .withContentType(template.contentType); + + for (const prop of template.properties) { + builder = builder.addProperty(prop.name, () => prop); + } + + return builder; + } + public get title() { return undefined; }