UNPKG

@siren-js/client

Version:
68 lines (67 loc) 2.46 kB
import { Action } from './models/action'; import { Serializer } from './serialize'; import { Href } from './utils'; import { Validator } from './validate'; export interface SubmitOptions { /** * Base URL used to resolve relative URIs */ baseUrl?: Href; /** * Additional HTTP request options */ requestInit?: RequestInit; /** * {@linkcode Serializer} used to serialize an {@link Action#fields `Action`'s `fields`} */ serializer?: Serializer; /** * {@linkcode Validator} used to validate an {@link Action#fields `Action`'s `fields`} */ validator?: Validator; } /** * Submits the given `action` by making an HTTP request according to `action`'s * `method` and `href`. * * If `fields` are present in `action`, they are validated via * `options.validator`. A {@linkcode ValidationError} is thrown when * `options.validator` returns a {@linkcode NegativeValidationResult}. If * `options.validator` is not provided, then validation automatically passes. * * If validation passes, the `fields` are then serialized according to * `options.serializer`, which receives `action`'s `type` and `fields`. If * `options.serializer` is not provided, the {@linkcode defaultSerializer} is * used. If `action.method` is `'GET'` or `'DELETE'`, the serialized content is * placed in the query string. Otherwise, the content is placed in the request * body. * * @example * import { defaultSerializer } from '@siren-js/client'; * * await submit(action, { * validator: (fields) => { * // ensure each field has a non-nullish value * if (fields.every((field) => field.value != null)) * return new PositiveValidationResult(); * else * return new NegativeValidationResult(); * }, * * serializer: (type, fields) => { * if (type === 'text/xml') * return { * content: // serialize fields to XML however you like... * }; * else * // rely on default serializer for any other type * return defaultSerializer(type, field); * } * }) * * @param action an {@linkcode Action} to submit * @param options a {@linkcode SubmitOptions} object * @returns a `Promise` that fulfills with an HTTP `Response` object * @throws a {@linkcode ValidationError} when `options.validator` returns a {@linkcode NegativeValidationResult} */ export declare function submit(action: Action, options?: SubmitOptions): Promise<Response>;