npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@contentgrid/hal-forms

v0.3.0

Published

HAL-FORMS models

Downloads

337

Readme

@contentgrid/hal-forms

Typescript models for reading the HAL-FORMS format.

Usage

The typical entrypoint for this library is resolveTemplate (or resolveTemplateRequired if you want an exception when a template is missing).

import { resolveTemplateRequired } from "@contentgrid/hal-forms"
import { HalFormsTemplateShape } from "@contentgrid/hal-forms/shape"
import { HalObjectShape } from "@contentgrid/hal/shape"

namespace myLibrary {
    export const response: HalObjectShape<{
        _templates?: {
            search?: HalFormsTemplateShape
        }
    }> = {
        _templates: {
            search: {
                method: "GET",
                target: "http://localhost/gifts/search",
                properties: [
                    {
                        name: "name",
                        required: true
                    }
                ]
            }
        }
    }
}


const template = resolveTemplateRequired(myLibrary.response, "search");

template.properties.forEach(property => {
    console.log(`Parameter: ${property.name}`)
})

Interactive form value management

When you have a form, you probably want to display it to your users in some way so they can enter values in your form fields.

The @contentgrid/hal-forms/values package is a simple utility to manage the form field values entered by users.

It uses the correct datatype belonging to each form field.

import { createValues } from "@contentgrid/hal-forms/values"

const templateValues = createValues(template); // template is a HalFormsTemplate

templateValues.values.forEach(value => {
    console.log(`Field ${value.property.name}: ${value.value}`)
})

templateValues = templateValues.withValue("name", "Jeff"); // Creates a new object with the value set

templateValues.values.forEach(value => {
    console.log(`Field ${value.property.name}: ${value.value}`)
})

Encoding HAL-FORMS into requests

After collecting user input, you probably want to send a request to the backend to submit the values entered in the form.

The @contentgrid/hal-forms/codecs sub-package encodes the values according to the content-type required by the HAL-FORMS template.

A default set of codecs is available, but you can also create your own set of codecs using HalFormsCodecs.builder().

The default set of codecs includes:

  • Encoding as request parameters for GET, HEAD and DELETE HTTP methods
  • "Nested" JSON encoding: form properties containing . are mapped to nested objects
  • Simple forms (x-www-form-urlencoded)
  • Multipart forms, for file upload (multipart/form-data)
  • text/uri-list for forms containing only URIs
import codecs from "@contentgrid/hal-forms/codecs";

const request = codecs.requireCodecFor(template) // template is a HalFormsTemplate
    .encode(templateValues); // templateValues is a HalFormValues

// The HAL-FORMS template method, target, contentType and values are encoded in request

// Put some additional headers on your request here
request.headers.set('Authorization', 'Basic ....');

// Perform the HTTP request
const response = await fetch(request);
console.log(response);

Decoding responses into HAL-FORMS

You may want to pre-fill some HAL-FORMS with values coming from a response received earlier from the backend.

The @contentgrid/hal-forms/codecs sub-package also provides decoders that can decode a response into values for a HAL-FORMS template.

This is especially useful for edit forms, where the current values of the backend are prefilled into the form before showing it to the user for modification.

import codecs from "@contentgrid/hal-forms/codecs";

const templateValues = codecs.requireCodecFor(template) // template is a HalFormsTemplate
    .decode({
        contentType: "application/json",
        body: { // body can be a string encoding a JSON object as well (or FormData)
            name: "Jeff"
        }
    });

// templateValues is the same as created using createValues(template), but with data filled in
templateValues.values.forEach(value => {
    console.log(`Field ${value.property.name}: ${value.value}`)
})

Shapes

The @contentgrid/hal-forms/shape sub-package provides POJO (plain old javascript object) types that can be used to represent the raw HAL-FORMS JSON data.

When using these shapes to define the response schema, HalFormsTemplateShape can take type parameters which determine the shape of the expected request and response bodies.

These types can be combined with @contentgrid/typed-fetch to statically type the expected request and response bodies for the form.

import { HalSlice } from "@contentgrid/hal";
import { resolveTemplateRequired } from "@contentgrid/hal-forms"
import { HalFormsTemplateShape } from "@contentgrid/hal-forms/shape"
import { HalObjectShape, HalSliceShape } from "@contentgrid/hal/shape"
import { fetch, createRequest, Representation } from "@contentgrid/typed-fetch"

namespace myLibrary {

    export interface Gift {
        id: number;
        name: string;
    }

    export interface GiftSearchRequest {
        name?: string;
    }

    export type GiftSearchResponse = HalSliceShape<Gift>;

    export const response: HalObjectShape<{
        _templates?: {
            search?: HalFormsTemplateShape<GiftSearchRequest, GiftSearchResponse>
        }
    }> = {
        _templates: {
            search: {
                method: "GET",
                target: "http://localhost/gifts/search",
                properties: [
                    {
                        name: "name",
                        required: true
                    }
                ]
            }
        }
    }
}

const template = resolveTemplateRequired(myLibrary.response, "search");

const request = createRequest(template.request, {
    body: Representation.json({
        name: "My friend"
    })
});

(async () => {
    const response = await fetch(request);
    if(response.ok) {
        const jsonData = await response.json();
        const page = new HalSlice(jsonData);
        page.items.forEach(item => {
            console.log(item.data.name);
        })
    }

})();

HAL-FORMS builder

In case you want to use the HAL-FORMS models to build your forms, but the API you're using does not have a HAL-FORMS template, you can construct a template by using @contentgrid/hal-forms/builder

import buildHalForm from "@contentgrid/hal-forms/builder"

const template = buildHalForm("GET", "http://localhost/gifts/search")
    .addProperty("name", property => property.withType("text").withRequired(true));

template.properties.forEach(property => {
    console.log(`Parameter: ${property.name}`)
})