UNPKG

@commercelayer/sdk

Version:
284 lines (280 loc) 10.9 kB
'use strict'; var chunkYY5ENJSH_cjs = require('./chunk-YY5ENJSH.cjs'); var chunkZWVME7CU_cjs = require('./chunk-ZWVME7CU.cjs'); var chunkPEC5CKS7_cjs = require('./chunk-PEC5CKS7.cjs'); var chunk7Z7FQA33_cjs = require('./chunk-7Z7FQA33.cjs'); var chunkIKHD5UQP_cjs = require('./chunk-IKHD5UQP.cjs'); var chunkJVF5KY2J_cjs = require('./chunk-JVF5KY2J.cjs'); // src/resource.ts var debug = chunkJVF5KY2J_cjs.debug_default("resource"); var ListResponse = class extends Array { meta; constructor(meta, data) { super(...data || []); this.meta = meta; } first() { return this.length ? this[0] : void 0; } last() { return this.length ? this[this.length - 1] : void 0; } get(index) { return this.length && index >= 0 ? this[index] : void 0; } hasNextPage() { return this.meta.currentPage < this.meta.pageCount; } hasPrevPage() { return this.meta.currentPage > 1; } getRecordCount() { return this.meta.recordCount; } getPageCount() { return this.meta.pageCount; } get recordCount() { return this.meta.recordCount; } get pageCount() { return this.meta.pageCount; } }; var ApiResourceAdapter = class _ApiResourceAdapter { static adapter; constructor() { } static init(config) { _ApiResourceAdapter.adapter = new ResourceAdapter(config); debug("resource adapter initialized"); return _ApiResourceAdapter.get(); } static get(config) { if (config) return _ApiResourceAdapter.init(config); else { if (_ApiResourceAdapter.adapter) return _ApiResourceAdapter.adapter; else throw new chunkIKHD5UQP_cjs.SdkError({ message: "Commerce Layer not initialized" }); } } static config(config) { _ApiResourceAdapter.get().config(config); } }; var ResourceAdapter = class { #client; #config = {}; constructor(config) { this.#client = chunkZWVME7CU_cjs.client_default.create(config); this.localConfig(config); } localConfig(config) { Object.assign(this.#config, config); } config(config) { debug("config %o", config); this.localConfig(config); this.#client.config(config); return this; } get client() { return this.#client; } async singleton(resource, params, options, path) { debug("singleton: %o, %O, %O", resource, params || {}, options || {}); const queryParams = chunkYY5ENJSH_cjs.generateQueryStringParams(params, resource); if (options?.params) Object.assign(queryParams, options?.params); const res = await this.#client.request("GET", `${path || resource.type}`, void 0, { ...options, params: queryParams }); const r = denormalize(res); return r; } async retrieve(resource, params, options) { debug("retrieve: %o, %O, %O", resource, params || {}, options || {}); const queryParams = chunkYY5ENJSH_cjs.generateQueryStringParams(params, resource); if (options?.params) Object.assign(queryParams, options?.params); const res = await this.#client.request("GET", `${resource.type}/${resource.id}`, void 0, { ...options, params: queryParams }); const r = denormalize(res); return r; } async list(resource, params, options) { debug("list: %o, %O, %O", resource, params || {}, options || {}); const queryParams = chunkYY5ENJSH_cjs.generateQueryStringParams(params, resource); if (options?.params) Object.assign(queryParams, options?.params); if (!queryParams["page[number]"]) queryParams["page[number]"] = "1"; const res = await this.#client.request("GET", `${resource.type}`, void 0, { ...options, params: queryParams }); const r = denormalize(res); const meta = { pageCount: Number(res.meta?.page_count), recordCount: Number(res.meta?.record_count), currentPage: params?.pageNumber || chunkPEC5CKS7_cjs.config_default.default.pageNumber, recordsPerPage: params?.pageSize || chunkPEC5CKS7_cjs.config_default.default.pageSize }; return new ListResponse(meta, r); } async create(resource, params, options) { debug("create: %o, %O, %O", resource, params || {}, options || {}); const queryParams = chunkYY5ENJSH_cjs.generateQueryStringParams(params, resource); if (options?.params) Object.assign(queryParams, options?.params); const data = normalize(resource); const res = await this.#client.request("POST", resource.type, data, { ...options, params: queryParams }); const r = denormalize(res); return r; } async update(resource, params, options) { debug("update: %o, %O, %O", resource, params || {}, options || {}); const queryParams = chunkYY5ENJSH_cjs.generateQueryStringParams(params, resource); if (options?.params) Object.assign(queryParams, options?.params); const data = normalize(resource); const res = await this.#client.request("PATCH", `${resource.type}/${resource.id}`, data, { ...options, params: queryParams }); const r = denormalize(res); return r; } async delete(resource, options) { debug("delete: %o, %O", resource, options || {}); await this.#client.request("DELETE", `${resource.type}/${resource.id}`, void 0, options); } async fetch(resource, path, params, options) { debug("fetch: %o, %O, %O", path, params || {}, options || {}); const queryParams = chunkYY5ENJSH_cjs.generateQueryStringParams(params, resource); if (options?.params) Object.assign(queryParams, options?.params); const res = await this.#client.request("GET", path, void 0, { ...options, params: queryParams }); const r = denormalize(res); if (Array.isArray(r)) { const p = params; const meta = { pageCount: Number(res.meta?.page_count), recordCount: Number(res.meta?.record_count), currentPage: p?.pageNumber || chunkPEC5CKS7_cjs.config_default.default.pageNumber, recordsPerPage: p?.pageSize || chunkPEC5CKS7_cjs.config_default.default.pageSize }; return new ListResponse(meta, r); } else return r; } }; var ApiResourceBase = class { static TYPE; #resources; constructor(adapter) { debug("new resource instance: %s", this.type()); if (adapter) this.#resources = adapter; } get resources() { return this.#resources || ApiResourceAdapter.get(); } relationshipOneToOne(id) { return id === null || typeof id === "string" ? { id, type: this.type() } : { id: id.id, type: this.type() }; } relationshipOneToMany(...ids) { return ids === null || ids.length === 0 || ids[0] === null ? [{ id: null, type: this.type() }] : ids.map((id) => { return { id, type: this.type() }; }); } path() { return this.type(); } // reference, reference_origin and metadata attributes are always updatable async update(resource, params, options) { return this.resources.update({ ...resource, type: this.type() }, params, options); } }; var ApiResource = class extends ApiResourceBase { async retrieve(id, params, options) { const resId = typeof id === "string" ? { type: this.type(), id } : id; if (!resId.id) throw new chunkIKHD5UQP_cjs.SdkError({ message: "Resource id cannot be blank" }); return this.resources.retrieve(resId, params, options); } async list(params, options) { return this.resources.list({ type: this.type() }, params, options); } async count(filter, options) { const params = { filters: chunkYY5ENJSH_cjs.isParamsList(filter) ? filter.filters : filter, pageNumber: 1, pageSize: 1 }; const response = await this.list(params, options); return Promise.resolve(response.meta.recordCount); } }; var ApiSingleton = class extends ApiResourceBase { async retrieve(params, options) { return this.resources.singleton({ type: this.type() }, params, options, this.path()); } }; var isResourceId = (resource) => { return resource?.type && resource.id && chunk7Z7FQA33_cjs.resourceList.includes(resource.type); }; var isResourceType = (resource) => { return resource && typeof resource.type !== "undefined" && resource.type && chunk7Z7FQA33_cjs.resourceList.includes(resource.type); }; // src/jsonapi.ts var debug2 = chunkJVF5KY2J_cjs.debug_default("jsonapi"); var denormalize = (response) => { if (!response) return response; let denormalizedResponse; if (response.links) delete response.links; const data = response.data; const included = response.included; if (!data) denormalizedResponse = data; else { if (Array.isArray(data)) denormalizedResponse = data.map((res) => denormalizeResource(res, included)); else denormalizedResponse = denormalizeResource(data, included); } return denormalizedResponse; }; var findIncluded = (rel, included = []) => { const inc = included.find((inc2) => { return rel.id === inc2.id && rel.type === inc2.type; }); return inc || rel; }; var denormalizeResource = (res, included, chain = []) => { debug2("denormalize resource: %O, %o", res, included || {}); if (!res) return res; const resource = { id: res.id, type: res.type, ...res.attributes }; if (res.relationships) Object.keys(res.relationships).forEach((key) => { const rel = res.relationships[key].data; if (rel) { if (chain.filter((r) => r.id === rel.id && r.type === rel.type).length >= chunkPEC5CKS7_cjs.config_default.jsonapi.maxResourceIncluded) resource[key] = rel; else { if (Array.isArray(rel)) resource[key] = rel.map((r) => denormalizeResource(findIncluded(r, included), included, [...chain, r])); else resource[key] = denormalizeResource(findIncluded(rel, included), included, [...chain, rel]); } } else if (rel === null) resource[key] = null; }); debug2("denormalized resource: %O", resource); return resource; }; var normalize = (resource) => { debug2("normalize resource: %O", resource); const attributes = {}; const relationships = {}; for (const field in resource) { if (["type", "id"].includes(field)) continue; const value = resource[field]; if (Array.isArray(value) && value.length === 1 && isResourceType(value[0]) && value[0].id === null) { relationships[field] = { data: [] }; } else if (value && isResourceType(value) && value.id === null) { relationships[field] = { data: null }; } else if (value && (isResourceId(value) || Array.isArray(value) && isResourceId(value[0]))) { relationships[field] = { data: value }; } else attributes[field] = value; } const normalized = { type: resource.type, attributes, relationships }; if (isResourceId(resource)) normalized.id = resource.id; debug2("normalized resource: %O", normalized); return normalized; }; exports.ApiResource = ApiResource; exports.ApiResourceAdapter = ApiResourceAdapter; exports.ApiSingleton = ApiSingleton; exports.denormalize = denormalize; exports.isResourceId = isResourceId; exports.isResourceType = isResourceType; exports.normalize = normalize; //# sourceMappingURL=chunk-U22VLCMN.cjs.map //# sourceMappingURL=chunk-U22VLCMN.cjs.map