UNPKG

ketting

Version:

Opiniated HATEAOS / Rest client.

66 lines 2.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ActionNotFound = exports.SimpleAction = void 0; const qs = require("querystring"); class SimpleAction { constructor(client, formInfo) { this.client = client; for (const [k, v] of Object.entries(formInfo)) { this[k] = v; } } /** * Execute the action or submit the form. */ async submit(formData) { const uri = new URL(this.uri); const newFormData = { ...formData }; for (const field of this.fields) { if (!(field.name in formData)) { if (field.value) { // We don't have perfect types for fields vs. FormData and how they // related, so 'any' is needed here. newFormData[field.name] = field.value; } else if (field.required) { throw new Error(`The ${field.name} field is required in this form`); } } } if (this.method === 'GET') { uri.search = qs.stringify(newFormData); const resource = this.client.go(uri.toString()); return resource.get(); } let body; switch (this.contentType) { case 'application/x-www-form-urlencoded': body = qs.stringify(newFormData); break; case 'application/json': body = JSON.stringify(newFormData); break; default: throw new Error(`Serializing mimetype ${this.contentType} is not yet supported in actions`); } const response = await this.client.fetcher.fetchOrThrow(uri.toString(), { method: this.method, body, headers: { 'Content-Type': this.contentType } }); const state = this.client.getStateForResponse(uri.toString(), response); return state; } field(name) { return this.fields.find(field => field.name === name); } } exports.SimpleAction = SimpleAction; class ActionNotFound extends Error { } exports.ActionNotFound = ActionNotFound; //# sourceMappingURL=action.js.map