UNPKG

@eldev/business-central-api

Version:

A Dynamics 365 Business Central client for TypeScript

102 lines 3.43 kB
import { BCError } from "../error/error.js"; import { parseSchema } from "../validation/parse-schema.js"; export class ApiPage { #schema; endpoint; client; constructor(client, endpoint, schema) { this.endpoint = endpoint; this.#schema = schema; this.client = client; } withCommands() { return this; } async getById(id, query) { const opts = { params: new URLSearchParams(query) }; return await this.client.requestWithSchema(this.#endpointWithId(id), this.#schema, opts); } async *list(query, pOpts) { let more = true; let skipToken = ""; let itemCount = 0; while (more) { const opts = { serverPageSize: pOpts?.serverPageLimit, }; opts.params = new URLSearchParams(query); if (skipToken) { opts.params.append("$skipToken", skipToken); } const data = (await this.client.request(this.endpoint, opts)); if (!data.value || !Array.isArray(data.value)) { const err = BCError.fromSchemaValidation([ { message: "Missing value property on list response.", path: "root.value", }, ]); err.responseData = data; throw err; } if (data["@odata.nextLink"]) { skipToken = URL.parse(data["@odata.nextLink"])?.searchParams.get("skipToken") || ""; } if (!data.value.length) { more = false; break; } for (const item of data.value) { const result = await parseSchema(this.#schema, item); if (result.issues) { throw BCError.fromSchemaValidation(result.issues); } yield result.data; itemCount++; if (pOpts?.maxResults && itemCount >= pOpts.maxResults) { more = false; break; } } } } async findOne(query) { let found = null; for await (const item of this.list(query, { serverPageLimit: 1 })) { found = item; break; } return found; } async update(id, updateCommand, query) { const data = await this.client.requestWithSchema(this.#endpointWithId(id), this.#schema, { method: "PATCH", payload: updateCommand, params: new URLSearchParams(query), }); return data; } async create(createCommand, query) { const data = await this.client.requestWithSchema(this.endpoint, this.#schema, { method: "POST", payload: createCommand, params: new URLSearchParams(query), }); return data; } async delete(id) { await this.client.request(this.#endpointWithId(id), { method: "DELETE" }); } async action(id, action) { const actionEndpoint = `${this.#endpointWithId(id)}/Microsoft.NAV.${action}`; await this.client.request(actionEndpoint, { method: "POST", }); } #endpointWithId(id) { return `${this.endpoint}(${id})`; } } //# sourceMappingURL=api-page.js.map