UNPKG

@prismicio/custom-types-client

Version:

JavaScript client to interact with the Prismic Custom Types API

366 lines (365 loc) 13.8 kB
"use strict"; var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); const errors = require("./errors.cjs"); const bulkUpdate = require("./bulkUpdate.cjs"); const DEFAULT_CUSTOM_TYPES_API_ENDPOINT = "https://customtypes.prismic.io"; const createPostFetchRequestInit = (body) => { return { method: "POST", body: JSON.stringify(body) }; }; const createClient = (...args) => new CustomTypesClient(...args); class CustomTypesClient { /** * Create a client for the Prismic Custom Types API. */ constructor(config) { /** * Name of the Prismic repository. */ __publicField(this, "repositoryName"); /** * The Prismic Custom Types API endpoint for the repository. The standard * Custom Types API endpoint will be used if no value is provided. * * @defaultValue `https://customtypes.prismic.io` */ __publicField(this, "endpoint"); /** * The secure token for accessing the Prismic Custom Types API. This is * required to call any Custom Type API methods. */ __publicField(this, "token"); /** * The function used to make network requests to the Prismic Custom Types API. * In environments where a global `fetch` function does not exist, such as * Node.js, this function must be provided. */ __publicField(this, "fetchFn"); /** * Options provided to the client's `fetch()` on all network requests. These * options will be merged with internally required options. They can also be * overriden on a per-query basis using the query's `fetchOptions` parameter. */ __publicField(this, "fetchOptions"); this.repositoryName = config.repositoryName; this.endpoint = config.endpoint || DEFAULT_CUSTOM_TYPES_API_ENDPOINT; this.token = config.token; this.fetchOptions = config.fetchOptions; if (/\/customtypes\/?$/.test(this.endpoint)) { this.endpoint = this.endpoint.replace(/\/customtypes\/?$/, ""); } if (typeof config.fetch === "function") { this.fetchFn = config.fetch; } else if (typeof globalThis.fetch === "function") { this.fetchFn = globalThis.fetch; } else { throw new errors.MissingFetchError("A valid fetch implementation was not provided. In environments where fetch is not available (including Node.js), a fetch implementation must be provided via a polyfill or the `fetch` config parameter."); } if (this.fetchFn === globalThis.fetch) { this.fetchFn = this.fetchFn.bind(globalThis); } } /** * Returns all Custom Types models from the Prismic repository. * * @typeParam TCustomType - The Custom Type returned from the API. * * @param params - Parameters to override the client's default configuration. * * @returns All Custom Type models from the Prismic repository. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. */ async getAllCustomTypes(params) { return await this.fetch("./customtypes", params); } /** * Returns a Custom Type model with a given ID from the Prismic repository. * * @typeParam TCustomType - The Custom Type returned from the API. * * @param id - ID of the Custom Type. * @param params - Parameters to override the client's default configuration. * * @returns The Custom Type model from the Prismic repository. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. * @throws {@link NotFoundError} Thrown if a Custom Type with the given ID * cannot be found. */ async getCustomTypeByID(id, params) { return await this.fetch(`./customtypes/${id}`, params); } /** * Inserts a Custom Type model to the Prismic repository. * * @typeParam TCustomType - The Custom Type to insert. * * @param customType - The Custom Type to insert. * @param params - Parameters to override the client's default configuration. * * @returns The inserted Custom Type. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. * @throws {@link InvalidPayloadError} Thrown if an invalid Custom Type is * provided. * @throws {@link ConflictError} Thrown if a Custom Type with the given ID * already exists. */ async insertCustomType(customType, params) { await this.fetch("./customtypes/insert", params, createPostFetchRequestInit(customType)); return customType; } /** * Updates a Custom Type model from the Prismic repository. * * @typeParam TCustomType - The updated Custom Type. * * @param customType - The updated Custom Type. * @param params - Parameters to override the client's default configuration. * * @returns The updated Custom Type. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. * @throws {@link InvalidPayloadError} Thrown if an invalid Custom Type is * provided. * @throws {@link NotFoundError} Thrown if a Custom Type with the given ID * cannot be found. */ async updateCustomType(customType, params) { await this.fetch("./customtypes/update", params, createPostFetchRequestInit(customType)); return customType; } /** * Removes a Custom Type model from the Prismic repository. * * @typeParam TCustomTypeID - The ID of the Custom Type. * * @param id - The ID of the Custom Type to remove. * @param params - Parameters to override the client's default configuration. * * @returns The ID of the removed Custom Type. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. */ async removeCustomType(id, params) { await this.fetch(`./customtypes/${id}`, params, { method: "DELETE" }); return id; } /** * Returns all Shared Slice models from the Prismic repository. * * @typeParam TSharedSliceModel - The Shared Slice model returned from the * API. * * @param params - Parameters to override the client's default configuration. * * @returns All Shared Slice models from the Prismic repository. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. */ async getAllSharedSlices(params) { return await this.fetch("./slices", params); } /** * Returns a Shared Slice model with a given ID from the Prismic repository. * * @typeParam TSharedSliceModel - The Shared Slice model returned from the * API. * * @param id - ID of the Shared Slice. * @param params - Parameters to override the client's default configuration. * * @returns The Shared Slice model from the Prismic repository. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. * @throws {@link NotFoundError} Thrown if a Shared Slice with the given ID * cannot be found. */ async getSharedSliceByID(id, params) { return await this.fetch(`./slices/${id}`, params); } /** * Inserts a Shared Slice model to the Prismic repository. * * @typeParam TSharedSliceModel - The Shared Slice model to insert. * * @param slice - The Shared Slice model to insert. * @param params - Parameters to override the client's default configuration. * * @returns The inserted Shared Slice model. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. * @throws {@link InvalidPayloadError} Thrown if an invalid Shared Slice model * is provided. * @throws {@link ConflictError} Thrown if a Shared Slice with the given ID * already exists. */ async insertSharedSlice(slice, params) { await this.fetch("./slices/insert", params, createPostFetchRequestInit(slice)); return slice; } /** * Updates a Shared Slice model from the Prismic repository. * * @typeParam TSharedSliceModel - The updated Shared Slice model. * * @param slice - The updated Shared Slice model. * @param params - Parameters to override the client's default configuration. * * @returns The updated Shared Slice model. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. * @throws {@link InvalidPayloadError} Thrown if an invalid Shared Slice model * is provided. * @throws {@link NotFoundError} Thrown if a Shared Slice with the given ID * cannot be found. */ async updateSharedSlice(slice, params) { await this.fetch("./slices/update", params, createPostFetchRequestInit(slice)); return slice; } /** * Removes a Shared Slice model from the Prismic repository. * * @typeParam TSharedSliceID - The ID of the Shared Slice. * * @param id - The ID of the Shared Slice to remove. * @param params - Parameters to override the client's default configuration. * * @returns The ID of the removed Shared Slice. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. */ async removeSharedSlice(id, params) { await this.fetch(`./slices/${id}`, params, { method: "DELETE" }); return id; } /** * Performs multiple insert, update, and/or delete operations in a single * transaction. * * @example * * ```ts * const bulkUpdateTransaction = createBulkUpdateTransaction(); * bulkUpdateTransaction.insertCustomType(myCustomType); * bulkUpdateTransaction.deleteSlice(mySlice); * * await client.bulkUpdate(bulkUpdateTransaction); * ``` * * @param operations - A `BulkUpdateTransaction` containing all operations or * an array of objects describing an operation. * @param params - Parameters that determine how the method behaves and for * overriding the client's default configuration. * * @returns An array of objects describing the operations. */ async bulkUpdate(operations, params) { const resolvedOperations = operations instanceof bulkUpdate.BulkUpdateTransaction ? operations.operations : operations; await this.fetch("./bulk-update", params, createPostFetchRequestInit({ changes: resolvedOperations })); return resolvedOperations; } /** * Performs a network request using the configured `fetch` function. It * assumes all successful responses will have a JSON content type. It also * normalizes unsuccessful network requests. * * @typeParam T - The JSON response. * * @param path - URL to the resource to fetch. * @param params - Parameters to override the client's default configuration. * @param requestInit - `RequestInit` overrides for the `fetch` request. * * @returns The response from the network request, if any. * * @throws {@link ForbiddenError} Thrown if the client is unauthorized to make * requests. * @throws {@link InvalidPayloadError} Thrown if the given body is invalid. * @throws {@link ConflictError} Thrown if an entity with the given ID already * exists. * @throws {@link NotFoundError} Thrown if the requested entity could not be * found. */ async fetch(path, params = {}, requestInit = {}) { var _a, _b, _c, _d; const endpoint = params.endpoint || this.endpoint; const url = new URL(path, endpoint.endsWith("/") ? endpoint : `${endpoint}/`).toString(); const res = await this.fetchFn(url, { ...this.fetchOptions, ...requestInit, ...params.fetchOptions, headers: { "Content-Type": "application/json", repository: params.repositoryName || this.repositoryName, Authorization: `Bearer ${params.token || this.token}`, ...(_a = this.fetchOptions) == null ? void 0 : _a.headers, ...requestInit.headers, ...(_b = params.fetchOptions) == null ? void 0 : _b.headers }, signal: ((_c = params.fetchOptions) == null ? void 0 : _c.signal) || params.signal || requestInit.signal || ((_d = this.fetchOptions) == null ? void 0 : _d.signal) }); switch (res.status) { case 200: { return await res.json(); } case 201: case 204: { return void 0; } case 400: { const text = await res.text(); throw new errors.InvalidPayloadError(text, { url, response: text }); } case 401: { const text = await res.text(); throw new errors.UnauthorizedError(text, { url, response: text }); } case 403: { const json = await res.json(); if ("hasExistingDocuments" in json && json.hasExistingDocuments) { throw new errors.BulkUpdateHasExistingDocumentsError("A custom type with published documents cannot be deleted. Delete all of the custom type's documents or remove the delete operation from the request before trying again.", { url, response: json }); } throw new errors.ForbiddenError(json.message, { url, response: json }); } case 409: { throw new errors.ConflictError("The provided ID is already used. A unique ID must be provided.", { url }); } case 404: case 422: { throw new errors.NotFoundError("An entity with a matching ID could not be found.", { url }); } } throw new errors.InvalidAPIResponse("An invalid API response was returned", { url }); } } exports.CustomTypesClient = CustomTypesClient; exports.createClient = createClient; //# sourceMappingURL=client.cjs.map