@commercelayer/provisioning-sdk 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/lib/index.d.mts +576 -0
  2. package/lib/index.d.ts +576 -0
  3. package/lib/index.js +1 -0
  4. package/lib/index.mjs +1 -0
  5. package/package.json +18 -19
  6. package/lib/cjs/api.d.ts +0 -43
  7. package/lib/cjs/api.js +0 -45
  8. package/lib/cjs/client.d.ts +0 -42
  9. package/lib/cjs/client.js +0 -149
  10. package/lib/cjs/commercelayer.d.ts +0 -39
  11. package/lib/cjs/commercelayer.js +0 -130
  12. package/lib/cjs/common.d.ts +0 -5
  13. package/lib/cjs/common.js +0 -12
  14. package/lib/cjs/config.d.ts +0 -15
  15. package/lib/cjs/config.js +0 -19
  16. package/lib/cjs/debug.d.ts +0 -3
  17. package/lib/cjs/debug.js +0 -38
  18. package/lib/cjs/error.d.ts +0 -31
  19. package/lib/cjs/error.js +0 -77
  20. package/lib/cjs/index.d.ts +0 -7
  21. package/lib/cjs/index.js +0 -13
  22. package/lib/cjs/interceptor.d.ts +0 -25
  23. package/lib/cjs/interceptor.js +0 -2
  24. package/lib/cjs/jsonapi.d.ts +0 -6
  25. package/lib/cjs/jsonapi.js +0 -94
  26. package/lib/cjs/model.d.ts +0 -11
  27. package/lib/cjs/model.js +0 -3
  28. package/lib/cjs/query.d.ts +0 -17
  29. package/lib/cjs/query.js +0 -52
  30. package/lib/cjs/resource.d.ts +0 -86
  31. package/lib/cjs/resource.js +0 -194
  32. package/lib/cjs/resources/api_credentials.d.ts +0 -59
  33. package/lib/cjs/resources/api_credentials.js +0 -33
  34. package/lib/cjs/resources/application_memberships.d.ts +0 -57
  35. package/lib/cjs/resources/application_memberships.js +0 -41
  36. package/lib/cjs/resources/memberships.d.ts +0 -58
  37. package/lib/cjs/resources/memberships.js +0 -45
  38. package/lib/cjs/resources/organizations.d.ts +0 -84
  39. package/lib/cjs/resources/organizations.js +0 -42
  40. package/lib/cjs/resources/permissions.d.ts +0 -52
  41. package/lib/cjs/resources/permissions.js +0 -34
  42. package/lib/cjs/resources/roles.d.ts +0 -47
  43. package/lib/cjs/resources/roles.js +0 -42
  44. package/lib/cjs/resources/user.d.ts +0 -29
  45. package/lib/cjs/resources/user.js +0 -20
  46. package/lib/cjs/resources/versions.d.ts +0 -22
  47. package/lib/cjs/resources/versions.js +0 -16
  48. package/lib/cjs/static.d.ts +0 -12
  49. package/lib/cjs/static.js +0 -51
  50. package/lib/cjs/util.d.ts +0 -9
  51. package/lib/cjs/util.js +0 -16
  52. package/lib/esm/api.d.ts +0 -43
  53. package/lib/esm/api.js +0 -31
  54. package/lib/esm/client.d.ts +0 -42
  55. package/lib/esm/client.js +0 -144
  56. package/lib/esm/commercelayer.d.ts +0 -39
  57. package/lib/esm/commercelayer.js +0 -101
  58. package/lib/esm/common.d.ts +0 -5
  59. package/lib/esm/common.js +0 -8
  60. package/lib/esm/config.d.ts +0 -15
  61. package/lib/esm/config.js +0 -17
  62. package/lib/esm/debug.d.ts +0 -3
  63. package/lib/esm/debug.js +0 -36
  64. package/lib/esm/error.d.ts +0 -31
  65. package/lib/esm/error.js +0 -69
  66. package/lib/esm/index.d.ts +0 -7
  67. package/lib/esm/index.js +0 -4
  68. package/lib/esm/interceptor.d.ts +0 -25
  69. package/lib/esm/interceptor.js +0 -1
  70. package/lib/esm/jsonapi.d.ts +0 -6
  71. package/lib/esm/jsonapi.js +0 -87
  72. package/lib/esm/model.d.ts +0 -11
  73. package/lib/esm/model.js +0 -2
  74. package/lib/esm/query.d.ts +0 -17
  75. package/lib/esm/query.js +0 -45
  76. package/lib/esm/resource.d.ts +0 -86
  77. package/lib/esm/resource.js +0 -187
  78. package/lib/esm/resources/api_credentials.d.ts +0 -59
  79. package/lib/esm/resources/api_credentials.js +0 -31
  80. package/lib/esm/resources/application_memberships.d.ts +0 -57
  81. package/lib/esm/resources/application_memberships.js +0 -39
  82. package/lib/esm/resources/memberships.d.ts +0 -58
  83. package/lib/esm/resources/memberships.js +0 -43
  84. package/lib/esm/resources/organizations.d.ts +0 -84
  85. package/lib/esm/resources/organizations.js +0 -40
  86. package/lib/esm/resources/permissions.d.ts +0 -52
  87. package/lib/esm/resources/permissions.js +0 -32
  88. package/lib/esm/resources/roles.d.ts +0 -47
  89. package/lib/esm/resources/roles.js +0 -40
  90. package/lib/esm/resources/user.d.ts +0 -29
  91. package/lib/esm/resources/user.js +0 -18
  92. package/lib/esm/resources/versions.d.ts +0 -22
  93. package/lib/esm/resources/versions.js +0 -14
  94. package/lib/esm/static.d.ts +0 -12
  95. package/lib/esm/static.js +0 -25
  96. package/lib/esm/util.d.ts +0 -9
  97. package/lib/esm/util.js +0 -37
  98. package/lib/tsconfig.esm.tsbuildinfo +0 -1
  99. package/lib/tsconfig.tsbuildinfo +0 -1
package/lib/esm/error.js DELETED
@@ -1,69 +0,0 @@
1
- import axios from 'axios';
2
- var ErrorType;
3
- (function (ErrorType) {
4
- ErrorType["CLIENT"] = "client";
5
- ErrorType["REQUEST"] = "request";
6
- ErrorType["RESPONSE"] = "response";
7
- ErrorType["CANCEL"] = "cancel";
8
- ErrorType["PARSE"] = "parse";
9
- ErrorType["GENERIC"] = "generic";
10
- })(ErrorType || (ErrorType = {}));
11
- class SdkError extends Error {
12
- static isSdkError(error) {
13
- return error && [SdkError.NAME, ApiError.NAME].includes(error.name) && Object.values(ErrorType).includes(error.type);
14
- }
15
- constructor(error) {
16
- super(error.message);
17
- this.name = SdkError.NAME; // this.constructor.name
18
- this.type = error.type || ErrorType.GENERIC;
19
- }
20
- }
21
- SdkError.NAME = 'SdkError';
22
- class ApiError extends SdkError {
23
- static isApiError(error) {
24
- return SdkError.isSdkError(error) && (error.name === ApiError.NAME) && (error.type === ErrorType.RESPONSE);
25
- }
26
- constructor(error) {
27
- super({ ...error, type: ErrorType.RESPONSE });
28
- this.errors = [];
29
- this.name = ApiError.NAME; // this.constructor.name
30
- }
31
- first() {
32
- var _a;
33
- return (((_a = this.errors) === null || _a === void 0 ? void 0 : _a.length) > 0) ? this.errors[0] : undefined;
34
- }
35
- }
36
- ApiError.NAME = 'ApiError';
37
- const handleError = (error) => {
38
- let sdkError = new SdkError({ message: error.message });
39
- if (axios.isAxiosError(error)) {
40
- if (error.response) {
41
- // The request was made and the server responded with a status code that falls out of the range of 2xx
42
- const apiError = new ApiError(sdkError);
43
- apiError.type = ErrorType.RESPONSE;
44
- apiError.status = error.response.status;
45
- apiError.statusText = error.response.statusText;
46
- apiError.code = String(apiError.status);
47
- apiError.errors = error.response.data.errors;
48
- if (!apiError.message && apiError.statusText)
49
- apiError.message = apiError.statusText;
50
- sdkError = apiError;
51
- }
52
- else if (error.request) {
53
- // The request was made but no response was received
54
- // `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in node.js
55
- sdkError.type = ErrorType.REQUEST;
56
- sdkError.request = error.request;
57
- }
58
- else {
59
- // Something happened in setting up the request that triggered an Error
60
- sdkError.type = ErrorType.CLIENT;
61
- }
62
- }
63
- else if (axios.isCancel(error))
64
- sdkError.type = ErrorType.CANCEL;
65
- else
66
- sdkError.source = error;
67
- throw sdkError;
68
- };
69
- export { SdkError, ApiError, ErrorType, handleError };
@@ -1,7 +0,0 @@
1
- export { default, CommerceLayerProvisioning } from './commercelayer';
2
- export type { CommerceLayerProvisioningClient } from './commercelayer';
3
- export { CommerceLayerProvisioningStatic } from './static';
4
- export type { QueryParamsRetrieve, QueryParamsList, QueryParams } from './query';
5
- export type * from './model';
6
- export type { RequestObj, ResponseObj, ErrorObj, HeadersObj } from './interceptor';
7
- export type { SdkError, ApiError, ErrorType } from './error';
package/lib/esm/index.js DELETED
@@ -1,4 +0,0 @@
1
- // SDK
2
- export { default, CommerceLayerProvisioning } from './commercelayer';
3
- // Commerce Layer Provisioning static functions
4
- export { CommerceLayerProvisioningStatic } from './static';
@@ -1,25 +0,0 @@
1
- import type { AxiosError, AxiosInterceptorManager, AxiosRequestConfig, AxiosResponse, AxiosResponseHeaders, RawAxiosResponseHeaders } from 'axios';
2
- type InterceptorManager = {
3
- request: AxiosInterceptorManager<AxiosRequestConfig>;
4
- response: AxiosInterceptorManager<any>;
5
- };
6
- type RequestObj = AxiosRequestConfig;
7
- type RequestInterceptor = (request: RequestObj) => RequestObj | Promise<RequestObj>;
8
- type ResponseObj = AxiosResponse;
9
- type ResponseInterceptor = (response: ResponseObj) => ResponseObj;
10
- type ApiHeadersList = 'x-ratelimit-limit' | 'x-ratelimit-count' | 'x-ratelimit-period' | 'x-ratelimit-interval' | 'x-ratelimit-remaining';
11
- type ApiHeaders = {
12
- [key in ApiHeadersList]: string | number | boolean;
13
- };
14
- type HeadersObj = (AxiosResponseHeaders | RawAxiosResponseHeaders) & ApiHeaders;
15
- type ErrorObj = AxiosError;
16
- type ErrorInterceptor = (error: ErrorObj) => ErrorObj;
17
- type InterceptorType = 'request' | 'response';
18
- export type { InterceptorManager, RequestInterceptor, ResponseInterceptor, ErrorInterceptor, InterceptorType };
19
- export type { RequestObj, ResponseObj, ErrorObj, HeadersObj };
20
- type RawResponseReader = {
21
- id: number | undefined;
22
- rawResponse: ResponseObj | undefined;
23
- headers: HeadersObj | undefined;
24
- };
25
- export type { RawResponseReader };
@@ -1 +0,0 @@
1
- export {};
@@ -1,6 +0,0 @@
1
- import type { DocWithData, ResourceObject as JSONAPIObject } from 'jsonapi-typescript';
2
- import type { ResourceCreate, ResourceUpdate, ResourceId, ResourceType, Resource } from './resource';
3
- export type { DocWithData };
4
- declare const denormalize: <R extends Resource>(response: DocWithData) => R | R[];
5
- declare const normalize: (resource: (ResourceCreate & ResourceType) | (ResourceUpdate & ResourceId)) => JSONAPIObject;
6
- export { denormalize, normalize };
@@ -1,87 +0,0 @@
1
- import { isResourceId, isResourceType } from './common';
2
- import config from './config';
3
- import Debug from './debug';
4
- const debug = Debug('jsonapi');
5
- // DENORMALIZATION
6
- const denormalize = (response) => {
7
- let denormalizedResponse;
8
- if (response.links)
9
- delete response.links;
10
- const data = response.data;
11
- const included = response.included;
12
- if (!data)
13
- denormalizedResponse = data;
14
- else {
15
- if (Array.isArray(data))
16
- denormalizedResponse = data.map(res => denormalizeResource(res, included));
17
- else
18
- denormalizedResponse = denormalizeResource(data, included);
19
- }
20
- return denormalizedResponse;
21
- };
22
- const findIncluded = (rel, included = []) => {
23
- const inc = included.find(inc => {
24
- return (rel.id === inc.id) && (rel.type === inc.type);
25
- });
26
- return inc || rel;
27
- };
28
- const denormalizeResource = (res, included, chain = []) => {
29
- debug('denormalize resource: %O, %o', res, included || {});
30
- if (!res)
31
- return res;
32
- const resource = {
33
- id: res.id,
34
- type: res.type,
35
- ...res.attributes,
36
- };
37
- if (res.relationships)
38
- Object.keys(res.relationships).forEach(key => {
39
- const rel = res.relationships[key].data;
40
- if (rel) {
41
- if (chain.filter(r => (r.id === rel.id) && (r.type === rel.type)).length >= config.jsonapi.maxResourceIncluded)
42
- resource[key] = rel;
43
- else {
44
- if (Array.isArray(rel))
45
- resource[key] = rel.map((r) => denormalizeResource(findIncluded(r, included), included, [...chain, r]));
46
- else
47
- resource[key] = denormalizeResource(findIncluded(rel, included), included, [...chain, rel]);
48
- }
49
- }
50
- else if (rel === null)
51
- resource[key] = null;
52
- });
53
- debug('denormalized resource: %O', resource);
54
- return resource;
55
- };
56
- // NORMALIZATION
57
- const normalize = (resource) => {
58
- debug('normalize resource: %O', resource);
59
- const attributes = {};
60
- const relationships = {};
61
- for (const field in resource) {
62
- if (['type', 'id'].includes(field))
63
- continue;
64
- const value = resource[field];
65
- if (Array.isArray(value) && (value.length === 1) && isResourceType(value[0]) && (value[0].id === null)) {
66
- relationships[field] = { data: [] };
67
- }
68
- else if (value && isResourceType(value) && (value.id === null)) {
69
- relationships[field] = { data: null };
70
- }
71
- else if (value && (isResourceId(value) || (Array.isArray(value) && isResourceId(value[0])))) {
72
- relationships[field] = { data: value };
73
- }
74
- else
75
- attributes[field] = value;
76
- }
77
- const normalized = {
78
- type: resource.type,
79
- attributes,
80
- relationships
81
- };
82
- if (isResourceId(resource))
83
- normalized.id = resource.id;
84
- debug('normalized resource: %O', normalized);
85
- return normalized;
86
- };
87
- export { denormalize, normalize };
@@ -1,11 +0,0 @@
1
- /**
2
- * ©2024 Commerce Layer Inc.
3
- **/
4
- export type { ApiCredential, ApiCredentialCreate, ApiCredentialUpdate } from './resources/api_credentials';
5
- export type { ApplicationMembership, ApplicationMembershipCreate, ApplicationMembershipUpdate } from './resources/application_memberships';
6
- export type { Membership, MembershipCreate, MembershipUpdate } from './resources/memberships';
7
- export type { Organization, OrganizationCreate, OrganizationUpdate } from './resources/organizations';
8
- export type { Permission, PermissionCreate, PermissionUpdate } from './resources/permissions';
9
- export type { Role, RoleCreate, RoleUpdate } from './resources/roles';
10
- export type { User, UserUpdate } from './resources/user';
11
- export type { Version } from './resources/versions';
package/lib/esm/model.js DELETED
@@ -1,2 +0,0 @@
1
- export {};
2
- // ##__MODEL_TYPES_STOP__##
@@ -1,17 +0,0 @@
1
- import type { ResourceType } from "./resource";
2
- type QueryFilter = Record<string, string | number | boolean>;
3
- interface QueryParamsRetrieve {
4
- include?: string[];
5
- fields?: string[] | Record<string, string[]>;
6
- }
7
- interface QueryParamsList extends QueryParamsRetrieve {
8
- sort?: string[] | Record<string, 'asc' | 'desc'>;
9
- filters?: QueryFilter;
10
- pageNumber?: number;
11
- pageSize?: number;
12
- }
13
- type QueryParams = QueryParamsRetrieve | QueryParamsList;
14
- export type { QueryParamsRetrieve, QueryParamsList, QueryParams, QueryFilter };
15
- declare const isParamsList: (params: any) => params is QueryParamsList;
16
- declare const generateQueryStringParams: (params: QueryParamsRetrieve | QueryParamsList | undefined, res: string | ResourceType) => Record<string, string>;
17
- export { generateQueryStringParams, isParamsList };
package/lib/esm/query.js DELETED
@@ -1,45 +0,0 @@
1
- import Debug from './debug';
2
- const debug = Debug('query');
3
- const isParamsList = (params) => {
4
- return params && (params.filters || params.pageNumber || params.pageSize || params.sort);
5
- };
6
- const generateQueryStringParams = (params, res) => {
7
- debug('generate query string params: %O, %O', params, res);
8
- const qp = {};
9
- if (!params)
10
- return qp;
11
- // Include
12
- if (params.include)
13
- qp.include = params.include.join(',');
14
- // Fields
15
- if (params.fields) {
16
- if (Array.isArray(params.fields))
17
- params.fields = { [res.type || res]: params.fields };
18
- Object.entries(params.fields).forEach(([p, v]) => {
19
- qp[`fields[${p}]`] = v.join(',');
20
- });
21
- }
22
- if (isParamsList(params)) {
23
- // Sort
24
- if (params.sort) {
25
- if (Array.isArray(params.sort))
26
- qp.sort = params.sort.join(',');
27
- else
28
- qp.sort = Object.entries(params.sort).map(([k, v]) => `${v === 'desc' ? '-' : ''}${k}`).join(',');
29
- }
30
- // Page
31
- if (params.pageNumber)
32
- qp['page[number]'] = String(params.pageNumber);
33
- if (params.pageSize)
34
- qp['page[size]'] = String(params.pageSize);
35
- // Filters
36
- if (params.filters) {
37
- Object.entries(params.filters).forEach(([p, v]) => {
38
- qp[`filter[q][${p}]`] = String(v);
39
- });
40
- }
41
- }
42
- debug('query string params: %O', qp);
43
- return qp;
44
- };
45
- export { generateQueryStringParams, isParamsList };
@@ -1,86 +0,0 @@
1
- import { type ApiClientInitConfig } from './client';
2
- import type { QueryParamsRetrieve, QueryParamsList, QueryFilter, QueryParams } from './query';
3
- import type { ResourceTypeLock } from './api';
4
- import type { InterceptorManager } from './interceptor';
5
- type ResourceNull = {
6
- id: null;
7
- } & ResourceType;
8
- type ResourceRel = ResourceId | ResourceNull;
9
- type Metadata = Record<string, any>;
10
- interface ResourceType {
11
- readonly type: ResourceTypeLock;
12
- }
13
- interface ResourceId extends ResourceType {
14
- readonly id: string;
15
- }
16
- interface ResourceBase {
17
- reference?: string | null;
18
- reference_origin?: string | null;
19
- metadata?: Metadata;
20
- }
21
- interface Resource extends ResourceBase, ResourceId {
22
- readonly created_at: string;
23
- readonly updated_at: string;
24
- }
25
- interface ResourceCreate extends ResourceBase {
26
- }
27
- interface ResourceUpdate extends ResourceBase {
28
- readonly id: string;
29
- }
30
- type ListMeta = {
31
- readonly pageCount: number;
32
- readonly recordCount: number;
33
- readonly currentPage: number;
34
- readonly recordsPerPage: number;
35
- };
36
- declare class ListResponse<R> extends Array<R> {
37
- readonly meta: ListMeta;
38
- constructor(meta: ListMeta, data: R[]);
39
- first(): R | undefined;
40
- last(): R | undefined;
41
- get(index: number): R | undefined;
42
- hasNextPage(): boolean;
43
- hasPrevPage(): boolean;
44
- getRecordCount(): number;
45
- getPageCount(): number;
46
- get recordCount(): number;
47
- get pageCount(): number;
48
- }
49
- export type { Metadata, ResourceType, ResourceId, Resource, ResourceCreate, ResourceUpdate, ListResponse, ListMeta, ResourceRel };
50
- type ResourceAdapterConfig = {};
51
- type ResourcesInitConfig = ResourceAdapterConfig & ApiClientInitConfig;
52
- type ResourcesConfig = Partial<ResourcesInitConfig>;
53
- declare class ResourceAdapter {
54
- #private;
55
- constructor(config: ResourcesInitConfig);
56
- get interceptors(): InterceptorManager;
57
- private localConfig;
58
- config(config: ResourcesConfig): ResourceAdapter;
59
- retrieve<R extends Resource>(resource: ResourceId | ResourceType, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<R>;
60
- list<R extends Resource>(resource: ResourceType, params?: QueryParamsList, options?: ResourcesConfig): Promise<ListResponse<R>>;
61
- create<C extends ResourceCreate, R extends Resource>(resource: C & ResourceType, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<R>;
62
- update<U extends ResourceUpdate, R extends Resource>(resource: U & ResourceId, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<R>;
63
- delete(resource: ResourceId, options?: ResourcesConfig): Promise<void>;
64
- fetch<R extends Resource>(resource: string | ResourceType, path: string, params?: QueryParams, options?: ResourcesConfig): Promise<R | ListResponse<R>>;
65
- action(cmd: 'post' | 'patch', path: string, payload?: any, options?: ResourcesConfig): Promise<void>;
66
- }
67
- declare abstract class ApiResourceBase<R extends Resource> {
68
- static readonly TYPE: ResourceTypeLock;
69
- protected readonly resources: ResourceAdapter;
70
- constructor(adapter: ResourceAdapter);
71
- abstract relationship(id: string | ResourceId | null): ResourceRel;
72
- abstract type(): ResourceTypeLock;
73
- parse(resource: string): R | R[];
74
- update(resource: ResourceUpdate, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<R>;
75
- }
76
- declare abstract class ApiResource<R extends Resource> extends ApiResourceBase<R> {
77
- retrieve(id: string | ResourceId, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<R>;
78
- list(params?: QueryParamsList, options?: ResourcesConfig): Promise<ListResponse<R>>;
79
- count(filter?: QueryFilter | QueryParamsList, options?: ResourcesConfig): Promise<number>;
80
- }
81
- declare abstract class ApiSingleton<R extends Resource> extends ApiResourceBase<R> {
82
- retrieve(params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<R>;
83
- }
84
- export default ResourceAdapter;
85
- export { ApiResource, ApiSingleton };
86
- export type { ResourcesConfig, ResourcesInitConfig };
@@ -1,187 +0,0 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _ResourceAdapter_client, _ResourceAdapter_config;
13
- import ApiClient from './client';
14
- import { denormalize, normalize } from './jsonapi';
15
- import { generateQueryStringParams, isParamsList } from './query';
16
- import config from './config';
17
- import { ErrorType, SdkError } from './error';
18
- import { CommerceLayerProvisioningStatic } from './static';
19
- import Debug from './debug';
20
- const debug = Debug('resource');
21
- class ListResponse extends Array {
22
- constructor(meta, data) {
23
- super(...(data || []));
24
- this.meta = meta;
25
- }
26
- first() { return this.length ? this[0] : undefined; }
27
- last() { return this.length ? this[this.length - 1] : undefined; }
28
- get(index) { return (this.length && (index >= 0)) ? this[index] : undefined; }
29
- hasNextPage() { return (this.meta.currentPage < this.meta.pageCount); }
30
- hasPrevPage() { return (this.meta.currentPage > 1); }
31
- getRecordCount() { return this.meta.recordCount; }
32
- getPageCount() { return this.meta.pageCount; }
33
- get recordCount() { return this.meta.recordCount; }
34
- get pageCount() { return this.meta.pageCount; }
35
- }
36
- class ResourceAdapter {
37
- constructor(config) {
38
- _ResourceAdapter_client.set(this, void 0);
39
- _ResourceAdapter_config.set(this, {});
40
- __classPrivateFieldSet(this, _ResourceAdapter_client, ApiClient.create(config), "f");
41
- this.localConfig(config);
42
- }
43
- get interceptors() { return __classPrivateFieldGet(this, _ResourceAdapter_client, "f").interceptors; }
44
- localConfig(config) {
45
- // if (typeof config.xyz !== 'undefined') this.#config.xyz = config.xyz
46
- }
47
- config(config) {
48
- debug('config %o', config);
49
- // ResourceAdapter config
50
- this.localConfig(config);
51
- // Client config
52
- __classPrivateFieldGet(this, _ResourceAdapter_client, "f").config(config);
53
- return this;
54
- }
55
- /*
56
- get clientInstance(): ApiClient {
57
- return this.#client
58
- }
59
- */
60
- async retrieve(resource, params, options) {
61
- const singleton = !('id' in resource) || CommerceLayerProvisioningStatic.isSingleton(resource.type);
62
- debug('retrieve:%s %o, %O, %O', (singleton ? ' singleton,' : ''), resource, params || {}, options || {});
63
- const queryParams = generateQueryStringParams(params, resource);
64
- if (options === null || options === void 0 ? void 0 : options.params)
65
- Object.assign(queryParams, options === null || options === void 0 ? void 0 : options.params);
66
- const path = `${resource.type}${singleton ? '' : `/${resource.id}`}`;
67
- const res = await __classPrivateFieldGet(this, _ResourceAdapter_client, "f").request('get', path, undefined, { ...options, params: queryParams });
68
- const r = denormalize(res);
69
- return r;
70
- }
71
- async list(resource, params, options) {
72
- var _a, _b;
73
- debug('list: %o, %O, %O', resource, params || {}, options || {});
74
- const queryParams = generateQueryStringParams(params, resource);
75
- if (options === null || options === void 0 ? void 0 : options.params)
76
- Object.assign(queryParams, options === null || options === void 0 ? void 0 : options.params);
77
- const res = await __classPrivateFieldGet(this, _ResourceAdapter_client, "f").request('get', `${resource.type}`, undefined, { ...options, params: queryParams });
78
- const r = denormalize(res);
79
- const meta = {
80
- pageCount: Number((_a = res.meta) === null || _a === void 0 ? void 0 : _a.page_count),
81
- recordCount: Number((_b = res.meta) === null || _b === void 0 ? void 0 : _b.record_count),
82
- currentPage: (params === null || params === void 0 ? void 0 : params.pageNumber) || config.default.pageNumber,
83
- recordsPerPage: (params === null || params === void 0 ? void 0 : params.pageSize) || config.default.pageSize
84
- };
85
- return new ListResponse(meta, r);
86
- }
87
- async create(resource, params, options) {
88
- debug('create: %o, %O, %O', resource, params || {}, options || {});
89
- const queryParams = generateQueryStringParams(params, resource);
90
- if (options === null || options === void 0 ? void 0 : options.params)
91
- Object.assign(queryParams, options === null || options === void 0 ? void 0 : options.params);
92
- const data = normalize(resource);
93
- const res = await __classPrivateFieldGet(this, _ResourceAdapter_client, "f").request('post', resource.type, data, { ...options, params: queryParams });
94
- const r = denormalize(res);
95
- return r;
96
- }
97
- async update(resource, params, options) {
98
- const singleton = !('id' in resource) || CommerceLayerProvisioningStatic.isSingleton(resource.type);
99
- debug('update:%s %o, %O, %O', (singleton ? ' singleton,' : ''), resource, params || {}, options || {});
100
- const queryParams = generateQueryStringParams(params, resource);
101
- if (options === null || options === void 0 ? void 0 : options.params)
102
- Object.assign(queryParams, options === null || options === void 0 ? void 0 : options.params);
103
- const path = `${resource.type}${singleton ? '' : `/${resource.id}`}`;
104
- const data = normalize(resource);
105
- const res = await __classPrivateFieldGet(this, _ResourceAdapter_client, "f").request('patch', path, data, { ...options, params: queryParams });
106
- const r = denormalize(res);
107
- return r;
108
- }
109
- async delete(resource, options) {
110
- debug('delete: %o, %O', resource, options || {});
111
- await __classPrivateFieldGet(this, _ResourceAdapter_client, "f").request('delete', `${resource.type}/${resource.id}`, undefined, options);
112
- }
113
- async fetch(resource, path, params, options) {
114
- var _a, _b;
115
- debug('fetch: %o, %O, %O', path, params || {}, options || {});
116
- const queryParams = generateQueryStringParams(params, resource);
117
- if (options === null || options === void 0 ? void 0 : options.params)
118
- Object.assign(queryParams, options === null || options === void 0 ? void 0 : options.params);
119
- const res = await __classPrivateFieldGet(this, _ResourceAdapter_client, "f").request('get', path, undefined, { ...options, params: queryParams });
120
- const r = denormalize(res);
121
- if (Array.isArray(r)) {
122
- const p = params;
123
- const meta = {
124
- pageCount: Number((_a = res.meta) === null || _a === void 0 ? void 0 : _a.page_count),
125
- recordCount: Number((_b = res.meta) === null || _b === void 0 ? void 0 : _b.record_count),
126
- currentPage: (p === null || p === void 0 ? void 0 : p.pageNumber) || config.default.pageNumber,
127
- recordsPerPage: (p === null || p === void 0 ? void 0 : p.pageSize) || config.default.pageSize
128
- };
129
- return new ListResponse(meta, r);
130
- }
131
- else
132
- return r;
133
- }
134
- async action(cmd, path, payload, options) {
135
- debug('action: %o %o, %O', cmd, path, options || {});
136
- const queryParams = {};
137
- if (options === null || options === void 0 ? void 0 : options.params)
138
- Object.assign(queryParams, options === null || options === void 0 ? void 0 : options.params);
139
- await __classPrivateFieldGet(this, _ResourceAdapter_client, "f").request(cmd, path, payload, { ...options, params: queryParams });
140
- }
141
- }
142
- _ResourceAdapter_client = new WeakMap(), _ResourceAdapter_config = new WeakMap();
143
- class ApiResourceBase {
144
- constructor(adapter) {
145
- debug('new resource instance: %s', this.type());
146
- this.resources = adapter;
147
- }
148
- parse(resource) {
149
- var _a, _b;
150
- try {
151
- const res = JSON.parse(resource);
152
- if (((_a = res.data) === null || _a === void 0 ? void 0 : _a.type) !== this.type())
153
- throw new SdkError({ message: `Invalid resource type [${(_b = res.data) === null || _b === void 0 ? void 0 : _b.type}]`, type: ErrorType.PARSE });
154
- return denormalize(res);
155
- }
156
- catch (error) {
157
- if (SdkError.isSdkError(error))
158
- throw error;
159
- else
160
- throw new SdkError({ message: `Payload parse error [${error.message}]`, type: ErrorType.PARSE });
161
- }
162
- }
163
- // reference, reference_origin and metadata attributes are always updatable
164
- async update(resource, params, options) {
165
- return this.resources.update({ ...resource, type: this.type() }, params, options);
166
- }
167
- }
168
- class ApiResource extends ApiResourceBase {
169
- async retrieve(id, params, options) {
170
- return this.resources.retrieve((typeof id === 'string') ? { type: this.type(), id } : id, params, options);
171
- }
172
- async list(params, options) {
173
- return this.resources.list({ type: this.type() }, params, options);
174
- }
175
- async count(filter, options) {
176
- const params = { filters: isParamsList(filter) ? filter.filters : filter, pageNumber: 1, pageSize: 1 };
177
- const response = await this.list(params, options);
178
- return Promise.resolve(response.meta.recordCount);
179
- }
180
- }
181
- class ApiSingleton extends ApiResourceBase {
182
- async retrieve(params, options) {
183
- return this.resources.retrieve({ type: this.type() }, params, options);
184
- }
185
- }
186
- export default ResourceAdapter;
187
- export { ApiResource, ApiSingleton };
@@ -1,59 +0,0 @@
1
- import { ApiResource } from '../resource';
2
- import type { Resource, ResourceCreate, ResourceUpdate, ResourceId, ResourcesConfig, ResourceRel } from '../resource';
3
- import type { QueryParamsRetrieve } from '../query';
4
- import type { Organization, OrganizationType } from './organizations';
5
- import type { Role, RoleType } from './roles';
6
- type ApiCredentialType = 'api_credentials';
7
- type ApiCredentialRel = ResourceRel & {
8
- type: ApiCredentialType;
9
- };
10
- type OrganizationRel = ResourceRel & {
11
- type: OrganizationType;
12
- };
13
- type RoleRel = ResourceRel & {
14
- type: RoleType;
15
- };
16
- interface ApiCredential extends Resource {
17
- readonly type: ApiCredentialType;
18
- name: string;
19
- kind: string;
20
- confidential: boolean;
21
- redirect_uri?: string | null;
22
- client_id: string;
23
- client_secret: string;
24
- scopes: string;
25
- expires_in?: number | null;
26
- mode?: string | null;
27
- custom?: boolean | null;
28
- organization?: Organization | null;
29
- role?: Role | null;
30
- }
31
- interface ApiCredentialCreate extends ResourceCreate {
32
- name: string;
33
- kind: string;
34
- redirect_uri?: string | null;
35
- expires_in?: number | null;
36
- mode?: string | null;
37
- custom?: boolean | null;
38
- organization: OrganizationRel;
39
- role?: RoleRel | null;
40
- }
41
- interface ApiCredentialUpdate extends ResourceUpdate {
42
- name?: string | null;
43
- redirect_uri?: string | null;
44
- expires_in?: number | null;
45
- role?: RoleRel | null;
46
- }
47
- declare class ApiCredentials extends ApiResource<ApiCredential> {
48
- static readonly TYPE: ApiCredentialType;
49
- create(resource: ApiCredentialCreate, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<ApiCredential>;
50
- update(resource: ApiCredentialUpdate, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<ApiCredential>;
51
- delete(id: string | ResourceId, options?: ResourcesConfig): Promise<void>;
52
- organization(apiCredentialId: string | ApiCredential, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<Organization>;
53
- role(apiCredentialId: string | ApiCredential, params?: QueryParamsRetrieve, options?: ResourcesConfig): Promise<Role>;
54
- isApiCredential(resource: any): resource is ApiCredential;
55
- relationship(id: string | ResourceId | null): ApiCredentialRel;
56
- type(): ApiCredentialType;
57
- }
58
- export default ApiCredentials;
59
- export type { ApiCredential, ApiCredentialCreate, ApiCredentialUpdate, ApiCredentialType };
@@ -1,31 +0,0 @@
1
- import { ApiResource } from '../resource';
2
- class ApiCredentials extends ApiResource {
3
- async create(resource, params, options) {
4
- return this.resources.create({ ...resource, type: ApiCredentials.TYPE }, params, options);
5
- }
6
- async update(resource, params, options) {
7
- return this.resources.update({ ...resource, type: ApiCredentials.TYPE }, params, options);
8
- }
9
- async delete(id, options) {
10
- await this.resources.delete((typeof id === 'string') ? { id, type: ApiCredentials.TYPE } : id, options);
11
- }
12
- async organization(apiCredentialId, params, options) {
13
- const _apiCredentialId = apiCredentialId.id || apiCredentialId;
14
- return this.resources.fetch({ type: 'organizations' }, `api_credentials/${_apiCredentialId}/organization`, params, options);
15
- }
16
- async role(apiCredentialId, params, options) {
17
- const _apiCredentialId = apiCredentialId.id || apiCredentialId;
18
- return this.resources.fetch({ type: 'roles' }, `api_credentials/${_apiCredentialId}/role`, params, options);
19
- }
20
- isApiCredential(resource) {
21
- return resource.type && (resource.type === ApiCredentials.TYPE);
22
- }
23
- relationship(id) {
24
- return ((id === null) || (typeof id === 'string')) ? { id, type: ApiCredentials.TYPE } : { id: id.id, type: ApiCredentials.TYPE };
25
- }
26
- type() {
27
- return ApiCredentials.TYPE;
28
- }
29
- }
30
- ApiCredentials.TYPE = 'api_credentials';
31
- export default ApiCredentials;