@stancer/stancer 1.0.2 → 1.1.1

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 (184) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/api-endpoint/http/fetch-http-client.d.ts.map +1 -1
  3. package/dist/api-endpoint/http/fetch-http-client.js +7 -1
  4. package/dist/api-endpoint/http/fetch-http-client.js.map +1 -1
  5. package/dist/core/common/handler/metadata-handler.d.ts +18 -0
  6. package/dist/core/common/handler/metadata-handler.d.ts.map +1 -0
  7. package/dist/core/common/handler/metadata-handler.js +19 -0
  8. package/dist/core/common/handler/metadata-handler.js.map +1 -0
  9. package/dist/event/model.d.ts +20 -0
  10. package/dist/event/model.d.ts.map +1 -0
  11. package/dist/event/model.js +30 -0
  12. package/dist/event/model.js.map +1 -0
  13. package/dist/index.d.ts +60 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +57 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/payment-intent/api-endpoint.d.ts +16 -1
  18. package/dist/payment-intent/api-endpoint.d.ts.map +1 -1
  19. package/dist/payment-intent/api-endpoint.js +2 -1
  20. package/dist/payment-intent/api-endpoint.js.map +1 -1
  21. package/dist/payment-intent/model.d.ts +3 -2
  22. package/dist/payment-intent/model.d.ts.map +1 -1
  23. package/dist/payment-intent/model.js +6 -0
  24. package/dist/payment-intent/model.js.map +1 -1
  25. package/dist/payment-intent/repository.d.ts +1 -1
  26. package/dist/payment-intent/repository.d.ts.map +1 -1
  27. package/dist/webhook/api-endpoint.d.ts +16 -0
  28. package/dist/webhook/api-endpoint.d.ts.map +1 -0
  29. package/dist/webhook/api-endpoint.js +33 -0
  30. package/dist/webhook/api-endpoint.js.map +1 -0
  31. package/dist/webhook/model.d.ts +35 -0
  32. package/dist/webhook/model.d.ts.map +1 -0
  33. package/dist/webhook/model.js +110 -0
  34. package/dist/webhook/model.js.map +1 -0
  35. package/dist/webhook/repository.d.ts +7 -0
  36. package/dist/webhook/repository.d.ts.map +1 -0
  37. package/dist/webhook/repository.js +10 -0
  38. package/dist/webhook/repository.js.map +1 -0
  39. package/dist/webhook/validator.d.ts +4 -0
  40. package/dist/webhook/validator.d.ts.map +1 -0
  41. package/dist/webhook/validator.js +16 -0
  42. package/dist/webhook/validator.js.map +1 -0
  43. package/package.json +33 -22
  44. package/dist/main.d.ts +0 -2
  45. package/dist/main.d.ts.map +0 -1
  46. package/dist/main.js +0 -2
  47. package/dist/main.js.map +0 -1
  48. package/reports/base.css +0 -362
  49. package/reports/block-navigation.js +0 -75
  50. package/reports/cobertura-coverage.xml +0 -18
  51. package/reports/favicon.png +0 -0
  52. package/reports/index.html +0 -177
  53. package/reports/junit.xml +0 -25
  54. package/reports/prettify.css +0 -101
  55. package/reports/prettify.js +0 -955
  56. package/reports/sort-arrow-sprite.png +0 -0
  57. package/reports/sorter.js +0 -205
  58. package/src/address/api-endpoint.ts +0 -30
  59. package/src/address/model.ts +0 -79
  60. package/src/address/repository.ts +0 -18
  61. package/src/address/validator.ts +0 -34
  62. package/src/api-endpoint/abstract-api-endpoint.ts +0 -310
  63. package/src/api-endpoint/configuration.ts +0 -125
  64. package/src/api-endpoint/http/fetch-http-client.ts +0 -29
  65. package/src/api-endpoint/http/http.ts +0 -75
  66. package/src/api-endpoint/http/index.ts +0 -2
  67. package/src/api-endpoint/version.ts +0 -4
  68. package/src/card/api-endpoint.ts +0 -39
  69. package/src/card/enum/funding.ts +0 -11
  70. package/src/card/enum/nature.ts +0 -7
  71. package/src/card/enum/network.ts +0 -16
  72. package/src/card/model.ts +0 -139
  73. package/src/card/repository.ts +0 -11
  74. package/src/card/validator.ts +0 -79
  75. package/src/core/abstract-model.ts +0 -126
  76. package/src/core/abstract-repository.ts +0 -201
  77. package/src/core/common/branded-type.ts +0 -15
  78. package/src/core/common/handler/date-handler.ts +0 -31
  79. package/src/core/common/handler/enum-handler.ts +0 -18
  80. package/src/core/common/handler/handler.ts +0 -64
  81. package/src/core/common/handler/id-handler.ts +0 -27
  82. package/src/core/common/id-validator.ts +0 -23
  83. package/src/core/common/mutation-tracked-object.ts +0 -49
  84. package/src/core/endpoint-interface.ts +0 -43
  85. package/src/core/error/base-error.ts +0 -1
  86. package/src/core/error/endpoint/api/api-conflict-error.ts +0 -7
  87. package/src/core/error/endpoint/api/api-error.ts +0 -10
  88. package/src/core/error/endpoint/api/api-not-found-error.ts +0 -7
  89. package/src/core/error/endpoint/api/api-unauthorized-error.ts +0 -7
  90. package/src/core/error/endpoint/api/api-unknown-error.ts +0 -7
  91. package/src/core/error/endpoint/api/api-validation-error.ts +0 -13
  92. package/src/core/error/endpoint/api/index.ts +0 -6
  93. package/src/core/error/endpoint/route-inaccessible-error.ts +0 -8
  94. package/src/core/error/unpopulated-error.ts +0 -3
  95. package/src/core/error/unsendable-error.ts +0 -3
  96. package/src/core/error/validation-error.ts +0 -3
  97. package/src/core/validator.ts +0 -129
  98. package/src/customer/api-endpoint.ts +0 -29
  99. package/src/customer/model.ts +0 -113
  100. package/src/customer/repository.ts +0 -14
  101. package/src/customer/validator.ts +0 -26
  102. package/src/payment/api-endpoint.ts +0 -118
  103. package/src/payment/enum/currency.ts +0 -14
  104. package/src/payment/enum/method.ts +0 -2
  105. package/src/payment/enum/status.ts +0 -21
  106. package/src/payment/model.ts +0 -378
  107. package/src/payment/repository.ts +0 -73
  108. package/src/payment/validator.ts +0 -96
  109. package/src/payment-intent/api-endpoint.ts +0 -123
  110. package/src/payment-intent/enum/status.ts +0 -21
  111. package/src/payment-intent/enum/threeds.ts +0 -2
  112. package/src/payment-intent/model.ts +0 -266
  113. package/src/payment-intent/repository.ts +0 -85
  114. package/src/payment-intent/validator.ts +0 -45
  115. package/src/payout/model.ts +0 -8
  116. package/src/refund/api-endpoint.ts +0 -33
  117. package/src/refund/enum/refund-status.ts +0 -11
  118. package/src/refund/model.ts +0 -90
  119. package/src/refund/repository.ts +0 -14
  120. package/src/refund/validator.ts +0 -44
  121. package/src/sepa/api-endpoint.ts +0 -26
  122. package/src/sepa/model.ts +0 -80
  123. package/src/sepa/repository.ts +0 -11
  124. package/src/sepa/validator.ts +0 -56
  125. package/test/fixtures/endpoint.stub.ts +0 -22
  126. package/test/fixtures/list-endpoint.stub.ts +0 -33
  127. package/test/fixtures/list-model.stub.ts +0 -24
  128. package/test/fixtures/model.stub.ts +0 -12
  129. package/test/functional/address.test.ts +0 -126
  130. package/test/functional/card.test.ts +0 -175
  131. package/test/functional/customer.test.ts +0 -174
  132. package/test/functional/payment-intent.test.ts +0 -215
  133. package/test/functional/payment.test.ts +0 -206
  134. package/test/functional/refund.test.ts +0 -112
  135. package/test/functional/sepa.test.ts +0 -136
  136. package/test/integration/stub-integration.test.ts +0 -88
  137. package/test/stub/stub-endpoint.ts +0 -42
  138. package/test/stub/stub-model.ts +0 -82
  139. package/test/stub/stub-repository.ts +0 -11
  140. package/test/test-helper.ts +0 -133
  141. package/test/unit/address/api-endpoint.test.ts +0 -134
  142. package/test/unit/address/fixtures.ts +0 -60
  143. package/test/unit/address/model.test.ts +0 -75
  144. package/test/unit/address/repository.test.ts +0 -148
  145. package/test/unit/address/validator.test.ts +0 -49
  146. package/test/unit/api-endpoint/http/fetch-http-client.test.ts +0 -44
  147. package/test/unit/api-endpoint/http/http.test.ts +0 -152
  148. package/test/unit/card/api-endpoint.test.ts +0 -170
  149. package/test/unit/card/card-helper.ts +0 -116
  150. package/test/unit/card/fixtures.ts +0 -87
  151. package/test/unit/card/model.test.ts +0 -167
  152. package/test/unit/card/repository.test.ts +0 -146
  153. package/test/unit/card/validator.test.ts +0 -96
  154. package/test/unit/core/common/mutation-tracked-object.test.ts +0 -24
  155. package/test/unit/customer/api-endpoint.test.ts +0 -143
  156. package/test/unit/customer/fixtures.ts +0 -73
  157. package/test/unit/customer/model.test.ts +0 -90
  158. package/test/unit/customer/repository.test.ts +0 -148
  159. package/test/unit/customer/validator.test.ts +0 -62
  160. package/test/unit/payment/api-endpoint.test.ts +0 -188
  161. package/test/unit/payment/fixtures.ts +0 -116
  162. package/test/unit/payment/model.test.ts +0 -240
  163. package/test/unit/payment/repository.test.ts +0 -270
  164. package/test/unit/payment/validator.test.ts +0 -137
  165. package/test/unit/payment-intent/api-endpoint.test.ts +0 -142
  166. package/test/unit/payment-intent/fixtures.ts +0 -94
  167. package/test/unit/payment-intent/model.test.ts +0 -157
  168. package/test/unit/payment-intent/repository.test.ts +0 -263
  169. package/test/unit/payment-intent/validator.test.ts +0 -136
  170. package/test/unit/refund/api-endpoint.test.ts +0 -129
  171. package/test/unit/refund/fixtures.ts +0 -58
  172. package/test/unit/refund/model.test.ts +0 -89
  173. package/test/unit/refund/repository.test.ts +0 -157
  174. package/test/unit/refund/validator.test.ts +0 -89
  175. package/test/unit/sepa/api-endpoint.test.ts +0 -170
  176. package/test/unit/sepa/fixture.ts +0 -62
  177. package/test/unit/sepa/model.test.ts +0 -86
  178. package/test/unit/sepa/repository.test.ts +0 -149
  179. package/test/unit/sepa/sepa-helper.ts +0 -71
  180. package/test/unit/sepa/validator.test.ts +0 -58
  181. package/test/unit/stub/stub-endpoint.test.ts +0 -236
  182. package/test/unit/stub/stub-list-endpoint.test.ts +0 -86
  183. package/test/unit/stub/stub-model.test.ts +0 -111
  184. package/test/unit/stub/stub-repository.test.ts +0 -144
Binary file
package/reports/sorter.js DELETED
@@ -1,205 +0,0 @@
1
- /* eslint-disable */
2
- var addSorting = (function () {
3
- 'use strict';
4
- var cols,
5
- currentSort = {
6
- index: 0,
7
- desc: false,
8
- };
9
-
10
- // returns the summary table element
11
- function getTable() {
12
- return document.querySelector('.coverage-summary');
13
- }
14
- // returns the thead element of the summary table
15
- function getTableHeader() {
16
- return getTable().querySelector('thead tr');
17
- }
18
- // returns the tbody element of the summary table
19
- function getTableBody() {
20
- return getTable().querySelector('tbody');
21
- }
22
- // returns the th element for nth column
23
- function getNthColumn(n) {
24
- return getTableHeader().querySelectorAll('th')[n];
25
- }
26
-
27
- function onFilterInput() {
28
- const searchValue = document.getElementById('fileSearch').value;
29
- const rows = document.getElementsByTagName('tbody')[0].children;
30
-
31
- // Try to create a RegExp from the searchValue. If it fails (invalid regex),
32
- // it will be treated as a plain text search
33
- let searchRegex;
34
- try {
35
- searchRegex = new RegExp(searchValue, 'i'); // 'i' for case-insensitive
36
- } catch (error) {
37
- searchRegex = null;
38
- }
39
-
40
- for (let i = 0; i < rows.length; i++) {
41
- const row = rows[i];
42
- let isMatch = false;
43
-
44
- if (searchRegex) {
45
- // If a valid regex was created, use it for matching
46
- isMatch = searchRegex.test(row.textContent);
47
- } else {
48
- // Otherwise, fall back to the original plain text search
49
- isMatch = row.textContent.toLowerCase().includes(searchValue.toLowerCase());
50
- }
51
-
52
- row.style.display = isMatch ? '' : 'none';
53
- }
54
- }
55
-
56
- // loads the search box
57
- function addSearchBox() {
58
- var template = document.getElementById('filterTemplate');
59
- var templateClone = template.content.cloneNode(true);
60
- templateClone.getElementById('fileSearch').oninput = onFilterInput;
61
- template.parentElement.appendChild(templateClone);
62
- }
63
-
64
- // loads all columns
65
- function loadColumns() {
66
- var colNodes = getTableHeader().querySelectorAll('th'),
67
- colNode,
68
- cols = [],
69
- col,
70
- i;
71
-
72
- for (i = 0; i < colNodes.length; i += 1) {
73
- colNode = colNodes[i];
74
- col = {
75
- key: colNode.getAttribute('data-col'),
76
- sortable: !colNode.getAttribute('data-nosort'),
77
- type: colNode.getAttribute('data-type') || 'string',
78
- };
79
- cols.push(col);
80
- if (col.sortable) {
81
- col.defaultDescSort = col.type === 'number';
82
- colNode.innerHTML = colNode.innerHTML + '<span class="sorter"></span>';
83
- }
84
- }
85
- return cols;
86
- }
87
- // attaches a data attribute to every tr element with an object
88
- // of data values keyed by column name
89
- function loadRowData(tableRow) {
90
- var tableCols = tableRow.querySelectorAll('td'),
91
- colNode,
92
- col,
93
- data = {},
94
- i,
95
- val;
96
- for (i = 0; i < tableCols.length; i += 1) {
97
- colNode = tableCols[i];
98
- col = cols[i];
99
- val = colNode.getAttribute('data-value');
100
- if (col.type === 'number') {
101
- val = Number(val);
102
- }
103
- data[col.key] = val;
104
- }
105
- return data;
106
- }
107
- // loads all row data
108
- function loadData() {
109
- var rows = getTableBody().querySelectorAll('tr'),
110
- i;
111
-
112
- for (i = 0; i < rows.length; i += 1) {
113
- rows[i].data = loadRowData(rows[i]);
114
- }
115
- }
116
- // sorts the table using the data for the ith column
117
- function sortByIndex(index, desc) {
118
- var key = cols[index].key,
119
- sorter = function (a, b) {
120
- a = a.data[key];
121
- b = b.data[key];
122
- return a < b ? -1 : a > b ? 1 : 0;
123
- },
124
- finalSorter = sorter,
125
- tableBody = document.querySelector('.coverage-summary tbody'),
126
- rowNodes = tableBody.querySelectorAll('tr'),
127
- rows = [],
128
- i;
129
-
130
- if (desc) {
131
- finalSorter = function (a, b) {
132
- return -1 * sorter(a, b);
133
- };
134
- }
135
-
136
- for (i = 0; i < rowNodes.length; i += 1) {
137
- rows.push(rowNodes[i]);
138
- tableBody.removeChild(rowNodes[i]);
139
- }
140
-
141
- rows.sort(finalSorter);
142
-
143
- for (i = 0; i < rows.length; i += 1) {
144
- tableBody.appendChild(rows[i]);
145
- }
146
- }
147
- // removes sort indicators for current column being sorted
148
- function removeSortIndicators() {
149
- var col = getNthColumn(currentSort.index),
150
- cls = col.className;
151
-
152
- cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, '');
153
- col.className = cls;
154
- }
155
- // adds sort indicators for current column being sorted
156
- function addSortIndicators() {
157
- getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted';
158
- }
159
- // adds event listeners for all sorter widgets
160
- function enableUI() {
161
- var i,
162
- el,
163
- ithSorter = function ithSorter(i) {
164
- var col = cols[i];
165
-
166
- return function () {
167
- var desc = col.defaultDescSort;
168
-
169
- if (currentSort.index === i) {
170
- desc = !currentSort.desc;
171
- }
172
- sortByIndex(i, desc);
173
- removeSortIndicators();
174
- currentSort.index = i;
175
- currentSort.desc = desc;
176
- addSortIndicators();
177
- };
178
- };
179
- for (i = 0; i < cols.length; i += 1) {
180
- if (cols[i].sortable) {
181
- // add the click event handler on the th so users
182
- // dont have to click on those tiny arrows
183
- el = getNthColumn(i).querySelector('.sorter').parentElement;
184
- if (el.addEventListener) {
185
- el.addEventListener('click', ithSorter(i));
186
- } else {
187
- el.attachEvent('onclick', ithSorter(i));
188
- }
189
- }
190
- }
191
- }
192
- // adds sorting functionality to the UI
193
- return function () {
194
- if (!getTable()) {
195
- return;
196
- }
197
- cols = loadColumns();
198
- loadData();
199
- addSearchBox();
200
- addSortIndicators();
201
- enableUI();
202
- };
203
- })();
204
-
205
- window.addEventListener('load', addSorting);
@@ -1,30 +0,0 @@
1
- import { ApiEndpoint, baseHandler } from '#api/abstract-api-endpoint.js';
2
- import { defaultHandler } from '#core/common/handler/handler.js';
3
- import { IdHandler } from '#core/common/handler/id-handler.js';
4
-
5
- import { type AddressData, AddressModel, type IdAddress } from './model.js';
6
-
7
- export class AddressApiEndpoint extends ApiEndpoint<AddressData> {
8
- protected override _handler = {
9
- ...baseHandler('created_at'),
10
- id: IdHandler<IdAddress>(AddressModel.regex),
11
- city: defaultHandler<AddressData['city']>('string', { postRequired: true }),
12
- country: defaultHandler<AddressData['country']>('string', { postRequired: true }),
13
- line1: defaultHandler<AddressData['line1']>('string'),
14
- line2: defaultHandler<AddressData['line2']>('string'),
15
- line3: defaultHandler<AddressData['line3']>('string'),
16
- metadata: defaultHandler<AddressData['metadata']>('string'),
17
- state: defaultHandler<AddressData['state']>('string'),
18
- zipCode: defaultHandler<AddressData['zipCode']>('string', { postRequired: true }),
19
- };
20
-
21
- constructor() {
22
- super({
23
- name: 'addresses',
24
- patchable: false,
25
- });
26
- }
27
- endpointUrl(id?: IdAddress) {
28
- return this._getResourceUri(id);
29
- }
30
- }
@@ -1,79 +0,0 @@
1
- import { AbstractModel, type ModelType } from '#core/abstract-model.js';
2
- import type { IdValue } from '#core/common/branded-type.js';
3
- import { validateID } from '#core/common/id-validator.js';
4
-
5
- export type IdAddress = IdValue<`addr_${string}`>;
6
- export const idAddress = (id: string) => validateID<IdAddress>(id, AddressModel.regex);
7
-
8
- export interface AddressData extends ModelType {
9
- city: string;
10
- country: string;
11
- id: IdAddress;
12
- line1: string;
13
- line2: string;
14
- line3: string;
15
- metadata: string;
16
- state: string;
17
- zipCode: string;
18
- }
19
- export class AddressModel extends AbstractModel<AddressData> {
20
- static regex = /^addr_[a-zA-Z0-9]{24}$/;
21
-
22
- get city() {
23
- return this._data.city;
24
- }
25
- get country() {
26
- return this._data.country;
27
- }
28
- get line1() {
29
- return this._data.line1;
30
- }
31
- get line2() {
32
- return this._data.line2;
33
- }
34
- get line3() {
35
- return this._data.line3;
36
- }
37
- get metadata() {
38
- return this._data.metadata;
39
- }
40
- get state() {
41
- return this._data.state;
42
- }
43
- get zipCode() {
44
- return this._data.zipCode;
45
- }
46
-
47
- setCity(value: string) {
48
- this._data['city'] = value;
49
- return this;
50
- }
51
- setCountry(value: string) {
52
- this._data['country'] = value;
53
- return this;
54
- }
55
- setLine1(value: string) {
56
- this._data['line1'] = value;
57
- return this;
58
- }
59
- setLine2(value: string) {
60
- this._data['line2'] = value;
61
- return this;
62
- }
63
- setLine3(value: string) {
64
- this._data['line3'] = value;
65
- return this;
66
- }
67
- setMetadata(value: string) {
68
- this._data['metadata'] = value;
69
- return this;
70
- }
71
- setState(value: string) {
72
- this._data['state'] = value;
73
- return this;
74
- }
75
- setZipCode(value: string) {
76
- this._data['zipCode'] = value;
77
- return this;
78
- }
79
- }
@@ -1,18 +0,0 @@
1
- import { AddressApiEndpoint } from '#address/api-endpoint.js';
2
- import { type AddressData, AddressModel } from '#address/model.js';
3
- import { addressValidator } from '#address/validator.js';
4
- import { AbstractRepository, type Repository } from '#core/abstract-repository.js';
5
- import type { EndpointInterface } from '#core/endpoint-interface.js';
6
-
7
- export class AddressRepository
8
- extends AbstractRepository<AddressData, AddressModel>
9
- implements Repository<AddressData, AddressModel>
10
- {
11
- constructor(endpoint?: EndpointInterface<AddressData>) {
12
- super({
13
- endpoint: endpoint ?? new AddressApiEndpoint(),
14
- validator: addressValidator,
15
- model: AddressModel,
16
- });
17
- }
18
- }
@@ -1,34 +0,0 @@
1
- import { type AddressData, AddressModel } from '#address/model.js';
2
- import { IdValidator } from '#core/common/id-validator.js';
3
- import { type Validator, createdAtValidator, goldilocksValidator } from '#core/validator.js';
4
-
5
- const cityMaxLength = 50;
6
- const cityMinLength = 1;
7
- const countryLength = 2;
8
- const lineMaxLength = 50;
9
- const lineMinLength = 1;
10
- const stateMaxLength = 3;
11
- const stateMinLength = 1;
12
- const zipCodeMaxLength = 16;
13
- const zipCodeMinLength = 2;
14
-
15
- const lineValidator = (lineName: string) => {
16
- return goldilocksValidator(lineName, { max: lineMaxLength, min: lineMinLength });
17
- };
18
-
19
- export const addressValidator: Validator<AddressData> = {
20
- id: IdValidator(AddressModel.regex),
21
- city: goldilocksValidator('city', { min: cityMinLength, max: cityMaxLength }),
22
- // country check for ISO 3166-1 alpha-2 country codes, because API wait for this precise type.
23
- country: goldilocksValidator('country', { size: countryLength }),
24
- createdAt: createdAtValidator,
25
- // Deleted is a system-managed field for soft deletes, not validated on client side.
26
- deleted: true,
27
- line1: lineValidator('line1'),
28
- line2: lineValidator('line2'),
29
- line3: lineValidator('line3'),
30
- // Metadata doesn't have strict set value, so we don't validate it, we let the API reject it.
31
- metadata: true,
32
- state: goldilocksValidator('state', { max: stateMaxLength, min: stateMinLength }),
33
- zipCode: goldilocksValidator('zipCode', { min: zipCodeMinLength, max: zipCodeMaxLength }),
34
- };
@@ -1,310 +0,0 @@
1
- import type { ModelData, ModelType } from '#core/abstract-model.js';
2
- import type { IdValue } from '#core/common/branded-type.js';
3
- import { timestampHandler } from '#core/common/handler/date-handler.js';
4
- import { type Handler, defaultHandler } from '#core/common/handler/handler.js';
5
- import type { EndpointInterface, ListParams } from '#core/endpoint-interface.js';
6
- import { StancerError } from '#core/error/base-error.js';
7
- import { StancerRouteInaccessibleError } from '#error/endpoint/route-inaccessible-error.js';
8
- import { UnsendableError } from '#error/unsendable-error.js';
9
-
10
- import { Configuration } from './configuration.js';
11
- import { Http } from './http/index.js';
12
-
13
- export interface Restriction {
14
- postable?: boolean;
15
- patchable?: boolean;
16
- listable?: boolean;
17
- deletable?: boolean;
18
- }
19
-
20
- export const baseHandler = (
21
- payloadName: string = 'createdAt',
22
- ): { [Property in keyof ModelData]: Handler<ModelData[Property]> } => {
23
- return {
24
- createdAt: { ...timestampHandler({ patchable: false, postable: false }), payloadName },
25
- deleted: defaultHandler<boolean>('boolean', { postable: false, patchable: false }),
26
- };
27
- };
28
- interface Config<Data> extends Restriction {
29
- name: string;
30
- deserializeResource: (resource: Record<string, unknown>) => Partial<Data>;
31
- postObjectSerializer: (obj: Partial<Data>) => object;
32
- patchObjectSerializer: (obj: Partial<Data>) => object;
33
- }
34
- type Handlers<T> = {
35
- [Property in keyof T]: Handler<T[Property]>;
36
- };
37
-
38
- export type ConfigParameter = {
39
- name: string;
40
- } & Restriction;
41
-
42
- type RangeParam = { start: number; end: number; limit: number; count: number; has_more: boolean };
43
- type Range<Data> = { range: RangeParam } & {
44
- [_key: string]: Partial<Data>[];
45
- };
46
-
47
- export const camelCaseTo_snake_case = (key: string): string =>
48
- key.replaceAll(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);
49
-
50
- export abstract class ApiEndpoint<Data extends ModelType> implements EndpointInterface<Data> {
51
- //#region constructor & property
52
- protected abstract _handler: Handlers<Data>;
53
-
54
- // All the property in our Data has the same name (cased in camelCase) as our API property, if not we specify a payloadName
55
- private _payloadKey = (key: keyof Data & string) => this._handler[key]?.payloadName ?? camelCaseTo_snake_case(key);
56
-
57
- private config: Config<Data> = {
58
- name: '',
59
- patchable: true,
60
- postable: true,
61
- listable: true,
62
- deletable: true,
63
-
64
- //Deserializer take an unknown resource and make it a Data from a specific model of our library
65
- deserializeResource: (resource: Record<string, unknown>): Partial<Data> => {
66
- // By definition Object.keys(specificArray) return array<keyof specificArray>
67
- const keys = Object.keys(this._handler) as Array<keyof Data & string>;
68
- return Object.fromEntries(
69
- keys
70
- .filter((key) => {
71
- return this._handler[key].gettable && resource[this._payloadKey(key)] !== undefined;
72
- })
73
- .map((key) => {
74
- return [key, this._handler[key].deserialize(resource[this._payloadKey(key)])];
75
- }),
76
- ) as Partial<Data>;
77
- },
78
- //Serializers take our model and make it readable by an external resource (api ...)
79
- postObjectSerializer: (data: Partial<Data>): Record<string, unknown> => {
80
- // By definition Object.keys(specificArray) return array<keyof specificArray>
81
- const keys = Object.keys(this._handler) as Array<keyof Data & string>;
82
-
83
- const partiallyRequired = keys.filter((key) => this._handler[key].postRequired === 'partial');
84
- const partialFullfilled = partiallyRequired.filter((key) => data[key] !== undefined);
85
- if (!partialFullfilled.length && partiallyRequired.length) {
86
- throw new UnsendableError(`one of the partially required data ( ${partiallyRequired.join(' or ')})`);
87
- }
88
- return Object.fromEntries(
89
- keys
90
- .filter((key) => {
91
- if (this._handler[key].postRequired === true && data[key] === undefined) {
92
- throw new UnsendableError(key);
93
- }
94
- return this._handler[key].postable && data[key] !== undefined;
95
- })
96
- .map((key) => [this._payloadKey(key), this._handler[key].serialize(data[key] as Data[keyof Data & string])]),
97
- );
98
- },
99
- patchObjectSerializer: (data: Partial<Data>): Record<string, unknown> => {
100
- // By definition Object.keys(specificArray) return array<keyof specificArray>
101
- const keys = Object.keys(this._handler) as Array<keyof Data & string>;
102
-
103
- const partiallyRequired = keys.filter((key) => this._handler[key].patchRequired === 'partial');
104
- const partialFullfilled = partiallyRequired.filter((key) => data[key] !== undefined);
105
- if (!partialFullfilled.length && partiallyRequired.length) {
106
- throw new UnsendableError(`one of the partially required data (${partiallyRequired.join(' or ')}) `);
107
- }
108
- return Object.fromEntries(
109
- keys
110
- .filter((key) => {
111
- if (this._handler[key].patchRequired === true && data[key] === undefined) {
112
- throw new UnsendableError(key);
113
- }
114
- return this._handler[key].patchable && data[key] !== undefined;
115
- })
116
- .map((key) => [this._payloadKey(key), this._handler[key].serialize(data[key] as Data[keyof Data & string])]),
117
- );
118
- },
119
- };
120
-
121
- constructor(config: ConfigParameter) {
122
- this.config.name = config.name;
123
- this.config.patchable = config.patchable ?? true;
124
- this.config.postable = config.postable ?? true;
125
- this.config.listable = config.listable ?? true;
126
- this.config.deletable = config.deletable ?? true;
127
- }
128
-
129
- //#endregion
130
- //#region endpoint interface
131
-
132
- public delete(id: IdValue) {
133
- if (!this.deletable) {
134
- throw new StancerRouteInaccessibleError('DELETE', this.config.name);
135
- }
136
- return this._httpClient
137
- .makeRequest(
138
- Http.createRequest({
139
- url: this._getResourceUri(id),
140
- method: 'DELETE',
141
- authenticated: true,
142
- }),
143
- )
144
- .then(Http.transformResponseToData<Record<string, unknown>>)
145
- .then(this.deserializeResource);
146
- }
147
-
148
- public get(id: IdValue): Promise<Partial<Data>> /*Gettable resources*/ {
149
- return this._httpClient
150
- .makeRequest(
151
- Http.createRequest({
152
- url: this._getResourceUri(id),
153
- method: 'GET',
154
- authenticated: true,
155
- }),
156
- )
157
- .then(Http.transformResponseToData<Record<string, unknown>>)
158
- .then(this.deserializeResource);
159
- }
160
-
161
- public send(id: IdValue | undefined, mutations: Partial<Data>): Promise<Partial<Data>> {
162
- if (!mutations || Object.keys(mutations).length === 0) {
163
- throw new StancerError('You cannot send a model whithout modification');
164
- }
165
- if (id) {
166
- return this.patch(id, mutations);
167
- }
168
- return this.post(mutations);
169
- }
170
-
171
- //#endregion
172
-
173
- public list({
174
- start = 0,
175
- limit = 100,
176
- end = 1000,
177
- filters = {},
178
- }: Partial<ListParams>): AsyncGenerator<Partial<Data>, void, Partial<Data>> {
179
- if (!this.listable) {
180
- throw new StancerRouteInaccessibleError('LIST', this.config.name);
181
- }
182
- return this.listGenerator({ start, limit, end, filters });
183
- }
184
-
185
- private createListUrl(endpoint: string, { start, limit, filters }: Omit<ListParams, 'end'>) {
186
- const url = new URL(endpoint + '/');
187
- url.searchParams.append('start', start.toString());
188
- url.searchParams.append('limit', limit.toString());
189
- for (const [key, value] of Object.entries(filters)) {
190
- url.searchParams.append(key, String(value));
191
- }
192
- return url;
193
- }
194
-
195
- private async *listGenerator(
196
- { start, limit, end, filters }: ListParams,
197
- endpoint = this._endpointBaseUrl,
198
- ): AsyncGenerator<Partial<Data>, void, Partial<Data>> {
199
- if (limit <= 0) {
200
- return;
201
- }
202
- for (let currentStart = start; currentStart - start < end; currentStart = currentStart + limit) {
203
- const url = this.createListUrl(endpoint, { start: currentStart, limit, filters });
204
- const endpointName = this.config.name;
205
-
206
- const data = await this._httpClient
207
- .makeRequest(
208
- Http.createRequest({
209
- url: url.toString(),
210
- method: 'GET',
211
- authenticated: true,
212
- }),
213
- )
214
- .then(Http.transformResponseToData<Range<Data>>)
215
- .then((result) => {
216
- if (!Array.isArray(result[endpointName])) {
217
- return;
218
- }
219
- const serializedData = result[endpointName].map((data) => this.deserializeResource(data)) ?? [];
220
-
221
- return { [endpointName]: serializedData, range: result.range };
222
- });
223
-
224
- if (!data || !Array.isArray(data[endpointName])) {
225
- return;
226
- }
227
-
228
- yield* data[endpointName];
229
-
230
- if (!data.range?.has_more) {
231
- return;
232
- }
233
- }
234
- }
235
-
236
- //#endregion
237
- //#region method
238
-
239
- private sendRequest(method: 'PATCH' | 'POST', url: string, data: object): Promise<Partial<Data>> {
240
- return this._httpClient
241
- .makeRequest(
242
- Http.createRequest({
243
- url,
244
- method,
245
- authenticated: true,
246
- headers: {
247
- 'content-type': 'application/json',
248
- },
249
- body: JSON.stringify(data),
250
- }),
251
- )
252
- .then(Http.transformResponseToData<Record<string, unknown>>)
253
- .then(this.deserializeResource);
254
- }
255
-
256
- public patch(id: IdValue, data: Partial<Data>) {
257
- if (!this.patchable) {
258
- throw new StancerRouteInaccessibleError('PATCH', this.config.name);
259
- }
260
- return this.sendRequest('PATCH', this._getResourceUri(id), this.patchObjectSerializer(data));
261
- }
262
-
263
- public post(data: Partial<Data>): Promise<Partial<Data>> {
264
- if (!this.postable) {
265
- throw new StancerRouteInaccessibleError('POST', this.config.name);
266
- }
267
- return this.sendRequest('POST', this._getResourceUri(), this.postObjectSerializer(data));
268
- }
269
- //#endregion
270
-
271
- //#region getter
272
-
273
- protected get _endpointBaseUrl() {
274
- return `${Configuration.baseUrl}/${this.config.name}`;
275
- }
276
- protected _getResourceUri(id?: IdValue) {
277
- return id ? `${this._endpointBaseUrl}/${id}` : `${this._endpointBaseUrl}/`;
278
- }
279
-
280
- protected get _httpClient() {
281
- return Configuration.httpClient;
282
- }
283
- get deletable() {
284
- return this.config.deletable;
285
- }
286
- get patchable() {
287
- return this.config.patchable;
288
- }
289
-
290
- get postable() {
291
- return this.config.postable;
292
- }
293
-
294
- get listable() {
295
- return this.config.listable;
296
- }
297
-
298
- get deserializeResource() {
299
- return this.config.deserializeResource;
300
- }
301
-
302
- get postObjectSerializer() {
303
- return this.config.postObjectSerializer;
304
- }
305
-
306
- get patchObjectSerializer() {
307
- return this.config.patchObjectSerializer;
308
- }
309
- //#endregion
310
- }