ng2-rest 21.0.11 → 21.0.15
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.
- package/README.md +0 -8
- package/browser/fesm2022/ng2-rest-browser.mjs +11 -9
- package/browser/fesm2022/ng2-rest-browser.mjs.map +1 -1
- package/browser/package.json +1 -1
- package/browser/types/ng2-rest-browser.d.ts +0 -2
- package/browser-prod/README.md +24 -0
- package/browser-prod/fesm2022/ng2-rest-browser.mjs +1804 -0
- package/browser-prod/fesm2022/ng2-rest-browser.mjs.map +1 -0
- package/browser-prod/types/ng2-rest-browser.d.ts +427 -0
- package/lib/axios-interceptors.js.map +1 -1
- package/lib/build-info._auto-generated_.d.ts +5 -1
- package/lib/build-info._auto-generated_.js +6 -2
- package/lib/build-info._auto-generated_.js.map +1 -1
- package/lib/env/env.angular-node-app.d.ts +30 -30
- package/lib/env/env.angular-node-app.js +32 -32
- package/lib/env/env.angular-node-app.js.map +1 -1
- package/lib/env/env.docs-webapp.d.ts +30 -30
- package/lib/env/env.docs-webapp.js +32 -32
- package/lib/env/env.docs-webapp.js.map +1 -1
- package/lib/env/env.electron-app.d.ts +30 -30
- package/lib/env/env.electron-app.js +32 -32
- package/lib/env/env.electron-app.js.map +1 -1
- package/lib/env/env.mobile-app.d.ts +30 -30
- package/lib/env/env.mobile-app.js +32 -32
- package/lib/env/env.mobile-app.js.map +1 -1
- package/lib/env/env.npm-lib-and-cli-tool.d.ts +30 -30
- package/lib/env/env.npm-lib-and-cli-tool.js +32 -32
- package/lib/env/env.npm-lib-and-cli-tool.js.map +1 -1
- package/lib/env/env.vscode-plugin.d.ts +30 -30
- package/lib/env/env.vscode-plugin.js +32 -32
- package/lib/env/env.vscode-plugin.js.map +1 -1
- package/lib/index._auto-generated_.js +1 -1
- package/lib/index._auto-generated_.js.map +1 -1
- package/lib/resource-service.d.ts +0 -1
- package/lib/resource-service.js +5 -7
- package/lib/resource-service.js.map +1 -1
- package/lib/rest-request.d.ts +0 -1
- package/lib/rest-request.js +4 -3
- package/lib/rest-request.js.map +1 -1
- package/lib-prod/axios-interceptors.d.ts +22 -0
- package/lib-prod/axios-interceptors.js +22 -0
- package/lib-prod/axios-interceptors.js.map +1 -0
- package/lib-prod/build-info._auto-generated_.d.ts +24 -0
- package/lib-prod/build-info._auto-generated_.js +30 -0
- package/lib-prod/build-info._auto-generated_.js.map +1 -0
- package/lib-prod/content-type.d.ts +5 -0
- package/lib-prod/content-type.js +15 -0
- package/lib-prod/content-type.js.map +1 -0
- package/lib-prod/cookie.d.ts +8 -0
- package/lib-prod/cookie.js +32 -0
- package/lib-prod/cookie.js.map +1 -0
- package/lib-prod/env/env.angular-node-app.d.ts +64 -0
- package/lib-prod/env/env.angular-node-app.js +71 -0
- package/lib-prod/env/env.angular-node-app.js.map +1 -0
- package/lib-prod/env/env.docs-webapp.d.ts +64 -0
- package/lib-prod/env/env.docs-webapp.js +71 -0
- package/lib-prod/env/env.docs-webapp.js.map +1 -0
- package/lib-prod/env/env.electron-app.d.ts +64 -0
- package/lib-prod/env/env.electron-app.js +71 -0
- package/lib-prod/env/env.electron-app.js.map +1 -0
- package/lib-prod/env/env.mobile-app.d.ts +64 -0
- package/lib-prod/env/env.mobile-app.js +71 -0
- package/lib-prod/env/env.mobile-app.js.map +1 -0
- package/lib-prod/env/env.npm-lib-and-cli-tool.d.ts +64 -0
- package/lib-prod/env/env.npm-lib-and-cli-tool.js +71 -0
- package/lib-prod/env/env.npm-lib-and-cli-tool.js.map +1 -0
- package/lib-prod/env/env.vscode-plugin.d.ts +64 -0
- package/lib-prod/env/env.vscode-plugin.js +71 -0
- package/lib-prod/env/env.vscode-plugin.js.map +1 -0
- package/lib-prod/env/index.d.ts +6 -0
- package/lib-prod/env/index.js +23 -0
- package/lib-prod/env/index.js.map +1 -0
- package/lib-prod/helpers.d.ts +11 -0
- package/lib-prod/helpers.js +26 -0
- package/lib-prod/helpers.js.map +1 -0
- package/lib-prod/index._auto-generated_.d.ts +0 -0
- package/lib-prod/index._auto-generated_.js +6 -0
- package/lib-prod/index._auto-generated_.js.map +1 -0
- package/lib-prod/index.d.ts +10 -0
- package/lib-prod/index.js +30 -0
- package/lib-prod/index.js.map +1 -0
- package/lib-prod/mapping.d.ts +13 -0
- package/lib-prod/mapping.js +280 -0
- package/lib-prod/mapping.js.map +1 -0
- package/lib-prod/models.d.ts +186 -0
- package/lib-prod/models.js +214 -0
- package/lib-prod/models.js.map +1 -0
- package/lib-prod/other/simple-resource.d.ts +30 -0
- package/lib-prod/other/simple-resource.js +138 -0
- package/lib-prod/other/simple-resource.js.map +1 -0
- package/lib-prod/params.d.ts +24 -0
- package/lib-prod/params.js +319 -0
- package/lib-prod/params.js.map +1 -0
- package/lib-prod/resource-service.d.ts +43 -0
- package/lib-prod/resource-service.js +210 -0
- package/lib-prod/resource-service.js.map +1 -0
- package/lib-prod/rest-headers.d.ts +58 -0
- package/lib-prod/rest-headers.js +141 -0
- package/lib-prod/rest-headers.js.map +1 -0
- package/lib-prod/rest-request.d.ts +29 -0
- package/lib-prod/rest-request.js +376 -0
- package/lib-prod/rest-request.js.map +1 -0
- package/lib-prod/rest.class.d.ts +36 -0
- package/lib-prod/rest.class.js +145 -0
- package/lib-prod/rest.class.js.map +1 -0
- package/package.json +9 -7
- package/tmp-environment.json +8 -4
- package/websql/fesm2022/ng2-rest-websql.mjs +11 -9
- package/websql/fesm2022/ng2-rest-websql.mjs.map +1 -1
- package/websql/package.json +1 -1
- package/websql/types/ng2-rest-websql.d.ts +0 -2
- package/websql-prod/README.md +24 -0
- package/websql-prod/fesm2022/ng2-rest-websql.mjs +1804 -0
- package/websql-prod/fesm2022/ng2-rest-websql.mjs.map +1 -0
- package/websql-prod/types/ng2-rest-websql.d.ts +427 -0
|
@@ -0,0 +1,1804 @@
|
|
|
1
|
+
import { from, firstValueFrom, Subject, Observable } from 'rxjs';
|
|
2
|
+
import { diffChars } from 'diff';
|
|
3
|
+
import { _, UtilsOs, CoreHelpers, CoreModels, Helpers as Helpers$1 } from 'tnp-core/websql-prod';
|
|
4
|
+
import { Log, Level } from 'ng2-logger/websql-prod';
|
|
5
|
+
import { walk } from 'lodash-walk-object/websql-prod';
|
|
6
|
+
import { CLASS, SYMBOL, Models as Models$1 } from 'typescript-class-helpers/websql-prod';
|
|
7
|
+
import { JSON10 } from 'json10/websql-prod';
|
|
8
|
+
import axios from 'axios';
|
|
9
|
+
|
|
10
|
+
class Cookie {
|
|
11
|
+
static get Instance() {
|
|
12
|
+
if (!Cookie.__instance) {
|
|
13
|
+
Cookie.__instance = new Cookie();
|
|
14
|
+
}
|
|
15
|
+
return Cookie.__instance;
|
|
16
|
+
}
|
|
17
|
+
constructor() {
|
|
18
|
+
}
|
|
19
|
+
read(name) {
|
|
20
|
+
var result = new RegExp('(?:^|; )' + encodeURIComponent(name) + '=([^;]*)').exec(document.cookie);
|
|
21
|
+
return result ? result[1] : null;
|
|
22
|
+
}
|
|
23
|
+
write(name, value, days) {
|
|
24
|
+
if (!days) {
|
|
25
|
+
days = 365 * 20;
|
|
26
|
+
}
|
|
27
|
+
var date = new Date();
|
|
28
|
+
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
|
|
29
|
+
var expires = "; expires=" + date.toUTCString();
|
|
30
|
+
document.cookie = name + "=" + value + expires + "; path=/";
|
|
31
|
+
}
|
|
32
|
+
remove(name) {
|
|
33
|
+
this.write(name, "", -1);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/* */
|
|
38
|
+
var Mapping;
|
|
39
|
+
(function (Mapping) {
|
|
40
|
+
function decode(json, autodetect = false) {
|
|
41
|
+
// console.log('DECODE isBrowser', HelpersLog.isBrowser)
|
|
42
|
+
if (_.isUndefined(json)) {
|
|
43
|
+
return void 0;
|
|
44
|
+
}
|
|
45
|
+
let mapping = decodeFromDecorator(_.isArray(json) ? _.first(json) : json, !autodetect);
|
|
46
|
+
if (autodetect) {
|
|
47
|
+
mapping = _.merge(getMappingNaive(json), mapping);
|
|
48
|
+
}
|
|
49
|
+
return mapping;
|
|
50
|
+
}
|
|
51
|
+
Mapping.decode = decode;
|
|
52
|
+
function encode(json, mapping, circular = []) {
|
|
53
|
+
if (_.isString(json) || _.isBoolean(json) || _.isNumber(json)) {
|
|
54
|
+
return json;
|
|
55
|
+
}
|
|
56
|
+
if (mapping['']) {
|
|
57
|
+
const decoratorMapping = getModelsMapping(CLASS.getBy(mapping['']));
|
|
58
|
+
mapping = _.merge(mapping, decoratorMapping);
|
|
59
|
+
}
|
|
60
|
+
let res;
|
|
61
|
+
if (_.isArray(circular) && circular.length > 0) {
|
|
62
|
+
res = setMappingCirc(json, mapping, circular);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
res = setMapping(json, mapping);
|
|
66
|
+
}
|
|
67
|
+
return res;
|
|
68
|
+
}
|
|
69
|
+
Mapping.encode = encode;
|
|
70
|
+
function decodeFromDecorator(json, production = false) {
|
|
71
|
+
const entityClass = CLASS.getFromObject(json);
|
|
72
|
+
const mappings = getModelsMapping(entityClass);
|
|
73
|
+
return mappings;
|
|
74
|
+
}
|
|
75
|
+
function getModelsMapping(entity) {
|
|
76
|
+
if (!_.isFunction(entity) || entity === Object) {
|
|
77
|
+
return {};
|
|
78
|
+
}
|
|
79
|
+
const className = CLASS.getName(entity);
|
|
80
|
+
// console.log(`getMaping for: '${className}' `)
|
|
81
|
+
let enityOWnMapping = _.isArray(entity[SYMBOL.MODELS_MAPPING])
|
|
82
|
+
? entity[SYMBOL.MODELS_MAPPING]
|
|
83
|
+
: [{ '': className }];
|
|
84
|
+
let res = {};
|
|
85
|
+
let parents = enityOWnMapping
|
|
86
|
+
.filter(m => !_.isUndefined(m['']) && m[''] !== className)
|
|
87
|
+
.map(m => m['']);
|
|
88
|
+
enityOWnMapping.reverse().forEach(m => {
|
|
89
|
+
m = _.cloneDeep(m);
|
|
90
|
+
// console.log(`'${className}' m:`, m)
|
|
91
|
+
Object.keys(m).forEach(key => {
|
|
92
|
+
const v = m[key];
|
|
93
|
+
const isArr = _.isArray(v);
|
|
94
|
+
const model = isArr ? _.first(v) : v;
|
|
95
|
+
if (parents.includes(model)) {
|
|
96
|
+
m[key] = isArr ? [className] : className;
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
res = _.merge(res, m);
|
|
100
|
+
});
|
|
101
|
+
res[''] = className;
|
|
102
|
+
// console.log(`mapping for ${className} : ${JSON.stringify(res)}`)
|
|
103
|
+
return res;
|
|
104
|
+
}
|
|
105
|
+
Mapping.getModelsMapping = getModelsMapping;
|
|
106
|
+
function add(o, path, mapping = {}) {
|
|
107
|
+
if (!o || Array.isArray(o) || typeof o !== 'object')
|
|
108
|
+
return;
|
|
109
|
+
const proptotypeObj = Object.getPrototypeOf(o);
|
|
110
|
+
if (!proptotypeObj) {
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
const objectClassName = CLASS.getName(proptotypeObj.constructor);
|
|
114
|
+
const resolveClass = CLASS.getBy(objectClassName);
|
|
115
|
+
if (!resolveClass) {
|
|
116
|
+
if (objectClassName !== 'Object') {
|
|
117
|
+
if (UtilsOs.isBrowser) {
|
|
118
|
+
console.error(`Cannot resolve class "${objectClassName}" while mapping.`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (!mapping[path])
|
|
124
|
+
mapping[path] = CLASS.getName(resolveClass);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* USE ONLY IN DEVELOPMENT
|
|
128
|
+
* @param c
|
|
129
|
+
* @param path
|
|
130
|
+
* @param mapping
|
|
131
|
+
* @param level
|
|
132
|
+
*/
|
|
133
|
+
function getMappingNaive(c, path = '', mapping = {}, level = 0) {
|
|
134
|
+
if (c === null || c === undefined) {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
/* */
|
|
138
|
+
/* */
|
|
139
|
+
/* */
|
|
140
|
+
/* */
|
|
141
|
+
// console.log({c})
|
|
142
|
+
if (Array.isArray(c)) {
|
|
143
|
+
c.forEach(c => getMappingNaive(c, path, mapping, level));
|
|
144
|
+
return mapping;
|
|
145
|
+
}
|
|
146
|
+
if (++level === 16)
|
|
147
|
+
return;
|
|
148
|
+
add(c, path, mapping);
|
|
149
|
+
for (var p in c) {
|
|
150
|
+
if (_.isFunction(c.hasOwnProperty) && c.hasOwnProperty(p)) {
|
|
151
|
+
const v = c[p];
|
|
152
|
+
if (Array.isArray(v) && v.length > 0) {
|
|
153
|
+
// reducer as impovement
|
|
154
|
+
v.forEach((elem, i) => {
|
|
155
|
+
// const currentPaht = [`path[${i}]`, p].filter(c => c.trim() != '').join('.');
|
|
156
|
+
const currentPaht = [path, p].filter(c => c.trim() != '').join('.');
|
|
157
|
+
getMappingNaive(elem, currentPaht, mapping, level);
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
else if (typeof v === 'object') {
|
|
161
|
+
const currentPaht = [path, p].filter(c => c.trim() != '').join('.');
|
|
162
|
+
add(v, currentPaht, mapping);
|
|
163
|
+
getMappingNaive(v, currentPaht, mapping, level);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return mapping;
|
|
168
|
+
}
|
|
169
|
+
function getMappingPathFrom(pathLodhas) {
|
|
170
|
+
if (!_.isString(pathLodhas)) {
|
|
171
|
+
return void 0;
|
|
172
|
+
}
|
|
173
|
+
const regex = /\[([0-9a-zA-Z]|\'|\")*\]/g;
|
|
174
|
+
pathLodhas = pathLodhas.replace(regex, '').replace('..', '.');
|
|
175
|
+
if (pathLodhas.startsWith('.')) {
|
|
176
|
+
pathLodhas = pathLodhas.slice(1);
|
|
177
|
+
}
|
|
178
|
+
return pathLodhas;
|
|
179
|
+
}
|
|
180
|
+
function setMappingCirc(json, mapping = {}, circular = []) {
|
|
181
|
+
const mainClassFn = !_.isArray(json) && CLASS.getBy(mapping['']);
|
|
182
|
+
// console.log(mapping)
|
|
183
|
+
walk.Object(json, (v, lodashPath, changeValue) => {
|
|
184
|
+
if (!_.isUndefined(v) && !_.isNull(v)) {
|
|
185
|
+
const mappingPath = getMappingPathFrom(lodashPath);
|
|
186
|
+
if (!_.isUndefined(mapping[mappingPath])) {
|
|
187
|
+
const isArray = _.isArray(mapping[mappingPath]);
|
|
188
|
+
if (!isArray) {
|
|
189
|
+
const className = isArray
|
|
190
|
+
? _.first(mapping[mappingPath])
|
|
191
|
+
: mapping[mappingPath];
|
|
192
|
+
const classFN = CLASS.getBy(className);
|
|
193
|
+
if (_.isFunction(classFN)) {
|
|
194
|
+
// console.log(`mapping: '${mappingPath}', lp: '${lodashPath}' class: '${className}' , set `, v.location)
|
|
195
|
+
changeValue(_.merge(new classFN(), v));
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
circular.forEach(c => {
|
|
202
|
+
const ref = _.get(json, c.circuralTargetPath);
|
|
203
|
+
_.set(json, c.pathToObj, ref);
|
|
204
|
+
});
|
|
205
|
+
if (_.isFunction(mainClassFn)) {
|
|
206
|
+
json = _.merge(new mainClassFn(), json);
|
|
207
|
+
}
|
|
208
|
+
return json;
|
|
209
|
+
}
|
|
210
|
+
function setMapping(json, mapping = {}) {
|
|
211
|
+
// console.log('mapping', mapping)
|
|
212
|
+
if (Array.isArray(json)) {
|
|
213
|
+
return json.map(j => {
|
|
214
|
+
return setMapping(j, mapping);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
const mainClassFn = CLASS.getBy(mapping['']);
|
|
218
|
+
for (const key in json) {
|
|
219
|
+
if (json.hasOwnProperty(key)) {
|
|
220
|
+
// if (mainClassFn && mainClassFn.name === 'Project') {
|
|
221
|
+
// // console.log(`OWn property: "${key}"`)
|
|
222
|
+
// }
|
|
223
|
+
if (_.isArray(json[key])) {
|
|
224
|
+
json[key] = json[key].map(arrObj => {
|
|
225
|
+
const objMapping = getModelsMapping(CLASS.getBy(mapping[key]));
|
|
226
|
+
return setMapping(arrObj, objMapping);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
else if (_.isObject(json[key])) {
|
|
230
|
+
const objMapping = getModelsMapping(CLASS.getBy(mapping[key]));
|
|
231
|
+
json[key] = setMapping(json[key], objMapping);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
// else {
|
|
235
|
+
// if (mainClassFn && mainClassFn.name === 'Project') {
|
|
236
|
+
// // console.log(`Not own property: "${key}"`)
|
|
237
|
+
// }
|
|
238
|
+
// }
|
|
239
|
+
}
|
|
240
|
+
Object.keys(mapping)
|
|
241
|
+
.filter(key => key !== '' && key.split('.').length >= 2)
|
|
242
|
+
.forEach(lodasPath => {
|
|
243
|
+
// console.log(`Loadsh path: ${lodasPath}`)
|
|
244
|
+
const objMapping = getModelsMapping(CLASS.getBy(mapping[lodasPath]));
|
|
245
|
+
const input = _.get(json, lodasPath);
|
|
246
|
+
if (!_.isUndefined(input)) {
|
|
247
|
+
const res = setMapping(input, objMapping);
|
|
248
|
+
_.set(json, lodasPath, res);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
if (!mainClassFn) {
|
|
252
|
+
return json;
|
|
253
|
+
}
|
|
254
|
+
return _.merge(new mainClassFn(), json);
|
|
255
|
+
}
|
|
256
|
+
function DefaultModelWithMapping(defaultModelValues, mapping) {
|
|
257
|
+
return function (target) {
|
|
258
|
+
if (!_.isArray(target[SYMBOL.MODELS_MAPPING])) {
|
|
259
|
+
target[SYMBOL.MODELS_MAPPING] = [];
|
|
260
|
+
}
|
|
261
|
+
target[SYMBOL.MODELS_MAPPING].push({
|
|
262
|
+
'': CLASS.getName(target),
|
|
263
|
+
});
|
|
264
|
+
if (_.isObject(mapping)) {
|
|
265
|
+
target[SYMBOL.MODELS_MAPPING] = target[SYMBOL.MODELS_MAPPING].concat(mapping);
|
|
266
|
+
Object.keys(mapping).forEach(key => {
|
|
267
|
+
const v = mapping;
|
|
268
|
+
if (_.isUndefined(v) || _.isFunction(v)) {
|
|
269
|
+
throw `
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
Class: '${target.name}'
|
|
273
|
+
[ng2rest] Bad mapping value for path: ${key} , please use type: <string> or [<string>]
|
|
274
|
+
`;
|
|
275
|
+
}
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
if (_.isObject(defaultModelValues)) {
|
|
279
|
+
const toMerge = {};
|
|
280
|
+
const describedTarget = CLASS.describeProperites(target).filter(prop => /^([a-zA-Z0-9]|\_|\#)+$/.test(prop));
|
|
281
|
+
// console.log(`describedTarget: ${describedTarget} for ${target.name}`)
|
|
282
|
+
describedTarget.forEach(propDefInConstr => {
|
|
283
|
+
if (defaultModelValues[propDefInConstr]) {
|
|
284
|
+
console.warn(`
|
|
285
|
+
|
|
286
|
+
CONFLICT: default value for property: "${propDefInConstr}"
|
|
287
|
+
in class "${target.name}" already defined as typescript
|
|
288
|
+
default class proprty value.
|
|
289
|
+
|
|
290
|
+
`);
|
|
291
|
+
}
|
|
292
|
+
else {
|
|
293
|
+
toMerge[propDefInConstr] = null; // TODO from toString I can't know that
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
// console.log(`merge "${JSON.stringify(target.prototype)}" with "${JSON.stringify(defaultModelValues)}"`)
|
|
297
|
+
target[SYMBOL.DEFAULT_MODEL] = _.merge(toMerge, defaultModelValues);
|
|
298
|
+
const propsToOmmit = Object.keys(target[SYMBOL.DEFAULT_MODEL]).filter(key => {
|
|
299
|
+
const descriptor = Object.getOwnPropertyDescriptor(target.prototype, key);
|
|
300
|
+
return !!descriptor;
|
|
301
|
+
});
|
|
302
|
+
_.merge(target.prototype, _.omit(target[SYMBOL.DEFAULT_MODEL], propsToOmmit));
|
|
303
|
+
// console.log(`DEFAULT VALUE MERGE for ${target.name}`)
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
Mapping.DefaultModelWithMapping = DefaultModelWithMapping;
|
|
308
|
+
})(Mapping || (Mapping = {}));
|
|
309
|
+
|
|
310
|
+
// @ts-ignore
|
|
311
|
+
class Helpers extends CoreHelpers {
|
|
312
|
+
static { this.JSON = JSON10; }
|
|
313
|
+
static get Mapping() {
|
|
314
|
+
return {
|
|
315
|
+
encode(json, mapping) {
|
|
316
|
+
return Mapping.encode(json, mapping);
|
|
317
|
+
},
|
|
318
|
+
decode(json, autodetect = false) {
|
|
319
|
+
return Mapping.decode(json, autodetect);
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
static checkValidUrl(url) {
|
|
324
|
+
let regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
|
|
325
|
+
return regex.test(url);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const log = Log.create('[ng2-rest] params', Level.__NOTHING);
|
|
330
|
+
/** check if string is a valid pattern */
|
|
331
|
+
function isValid(pattern) {
|
|
332
|
+
return (new RegExp('\/:[a-zA-Z]*', 'g')).test(pattern.replace('://', ''));
|
|
333
|
+
}
|
|
334
|
+
function check(url, pattern) {
|
|
335
|
+
if (!Helpers.checkValidUrl(url)) {
|
|
336
|
+
log.error(`Incorrect url: ${url}`);
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
if (url.charAt(url.length - 1) === '/')
|
|
340
|
+
url = url.slice(0, url.length - 2);
|
|
341
|
+
if (pattern.charAt(pattern.length - 1) === '/')
|
|
342
|
+
pattern = pattern.slice(0, url.length - 2);
|
|
343
|
+
pattern = pattern.replace(/\//g, '\/');
|
|
344
|
+
pattern = pattern.replace(new RegExp('\/:[a-zA-Z]*', 'g'), '.+');
|
|
345
|
+
let reg = new RegExp(pattern, 'g');
|
|
346
|
+
return reg.test(url);
|
|
347
|
+
}
|
|
348
|
+
function getModels(pattern) {
|
|
349
|
+
let m = pattern.match(new RegExp('[a-z-A-Z]*\/:', 'g'));
|
|
350
|
+
return m.map(p => p.replace('/:', ''));
|
|
351
|
+
}
|
|
352
|
+
function getRestPramsNames(pattern) {
|
|
353
|
+
if (pattern.charAt(pattern.length - 1) !== '/')
|
|
354
|
+
pattern = `${pattern}/`;
|
|
355
|
+
let m = pattern.match(new RegExp(':[a-zA-Z]*\/', 'g'));
|
|
356
|
+
let res = m.map(p => p.replace(':', '').replace('/', ''));
|
|
357
|
+
return res.filter(p => p.trim() !== '');
|
|
358
|
+
}
|
|
359
|
+
function containsModels(url, models) {
|
|
360
|
+
if (url.charAt(0) !== '/')
|
|
361
|
+
url = '/' + url;
|
|
362
|
+
// url = url.replace(new RegExp('\/', 'g'), '');
|
|
363
|
+
let res = models.filter(m => {
|
|
364
|
+
let word = '/' + m;
|
|
365
|
+
// log.d('word', word)
|
|
366
|
+
let iii = url.indexOf(word);
|
|
367
|
+
// log.d('iii', iii)
|
|
368
|
+
if (iii + word.length < url.length && url.charAt(iii + word.length) !== '/') {
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
if (iii !== -1) {
|
|
372
|
+
url = url.replace(new RegExp('\/' + m, 'g'), '');
|
|
373
|
+
return true;
|
|
374
|
+
}
|
|
375
|
+
return false;
|
|
376
|
+
}).length;
|
|
377
|
+
// log.d('containsModels', res);
|
|
378
|
+
return res === models.length;
|
|
379
|
+
}
|
|
380
|
+
function stars(n) {
|
|
381
|
+
let res = '';
|
|
382
|
+
for (let i = 0; i < n; i++)
|
|
383
|
+
res += '*';
|
|
384
|
+
return res;
|
|
385
|
+
}
|
|
386
|
+
function getRestParams(url, pattern) {
|
|
387
|
+
let res = {};
|
|
388
|
+
let models = getRestPramsNames(pattern);
|
|
389
|
+
// log.d('models', models);
|
|
390
|
+
models.forEach(m => {
|
|
391
|
+
pattern = pattern.replace(`:${m}`, stars(m.length));
|
|
392
|
+
});
|
|
393
|
+
let currentModel = void 0;
|
|
394
|
+
diffChars(pattern, url).forEach(d => {
|
|
395
|
+
// log.d('d', d);
|
|
396
|
+
if (d.added) {
|
|
397
|
+
if (!isNaN(Number(d.value)))
|
|
398
|
+
res[currentModel] = Number(d.value);
|
|
399
|
+
else if (d.value.trim() === 'true')
|
|
400
|
+
res[currentModel] = true;
|
|
401
|
+
else if (d.value.trim() === 'false')
|
|
402
|
+
res[currentModel] = false;
|
|
403
|
+
else
|
|
404
|
+
res[currentModel] = decodeURIComponent(d.value);
|
|
405
|
+
currentModel = void 0;
|
|
406
|
+
}
|
|
407
|
+
let m = d.value.replace(':', "");
|
|
408
|
+
// log.d('model m', m)
|
|
409
|
+
if (d.removed) {
|
|
410
|
+
currentModel = models.shift();
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
return res;
|
|
414
|
+
}
|
|
415
|
+
const regexisPath = /[^\..]+(\.[^\..]+)+/g;
|
|
416
|
+
/**
|
|
417
|
+
* Models like books/:id
|
|
418
|
+
*/
|
|
419
|
+
function cutUrlModel(params, models, output) {
|
|
420
|
+
if (models.length === 0)
|
|
421
|
+
return output.join('\/');
|
|
422
|
+
let m = models.pop();
|
|
423
|
+
let param = m.match(/:[a-zA-Z0-9\.]+/)[0].replace(':', '');
|
|
424
|
+
const paramIsPath = regexisPath.test(param);
|
|
425
|
+
// log.i('cut param', param)
|
|
426
|
+
let model = m.match(/[a-zA-Z0-9]+\//)[0].replace('\/', '');
|
|
427
|
+
if (params === void 0 ||
|
|
428
|
+
(paramIsPath ? _.get(params, param) === void 0 : params[param] === void 0) ||
|
|
429
|
+
param === 'undefined') {
|
|
430
|
+
output.length = 0;
|
|
431
|
+
output.unshift(model);
|
|
432
|
+
return cutUrlModel(params, models, output);
|
|
433
|
+
}
|
|
434
|
+
else {
|
|
435
|
+
if (paramIsPath) {
|
|
436
|
+
// log.i('param is path', param)
|
|
437
|
+
let mrep = m.replace(new RegExp(`:${param}`, 'g'), `${_.get(params, param)}`);
|
|
438
|
+
output.unshift(mrep);
|
|
439
|
+
return cutUrlModel(params, models, output);
|
|
440
|
+
}
|
|
441
|
+
else {
|
|
442
|
+
// log.i('param is normal', param)
|
|
443
|
+
let mrep = m.replace(new RegExp(`:${param}`, 'g'), `${params[param]}`);
|
|
444
|
+
output.unshift(mrep);
|
|
445
|
+
return cutUrlModel(params, models, output);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function interpolateParamsToUrl(params, url) {
|
|
450
|
+
const regexInt = /\[\[([^\..]+\.[^\..]+)+\]\]/g;
|
|
451
|
+
url = url.split('/').map(p => {
|
|
452
|
+
// log.d('url parts', p)
|
|
453
|
+
let isParam = p.startsWith(':');
|
|
454
|
+
if (isParam) {
|
|
455
|
+
let part = p.slice(1);
|
|
456
|
+
// log.d('url param part', p)
|
|
457
|
+
if (regexInt.test(part)) {
|
|
458
|
+
// let level = (url.split('.').length - 1)
|
|
459
|
+
part = part.replace('[[', '');
|
|
460
|
+
part = part.replace(']]', '');
|
|
461
|
+
}
|
|
462
|
+
return `:${part}`;
|
|
463
|
+
}
|
|
464
|
+
return p;
|
|
465
|
+
}).join('/');
|
|
466
|
+
// log.i('URL TO EXPOSE', url)
|
|
467
|
+
// log.i('params', params)
|
|
468
|
+
let slash = {
|
|
469
|
+
start: url.charAt(0) === '\/',
|
|
470
|
+
end: url.charAt(url.length - 1) === '\/'
|
|
471
|
+
};
|
|
472
|
+
let morePramsOnEnd = url.match(/(\/:[a-zA-Z0-9\.]+){2,10}/g);
|
|
473
|
+
if (morePramsOnEnd && (Array.isArray(morePramsOnEnd) && morePramsOnEnd.length === 1)) {
|
|
474
|
+
// log.i('morePramsOnEnd', morePramsOnEnd)
|
|
475
|
+
let m = morePramsOnEnd[0];
|
|
476
|
+
let match = m.match(/\/:[a-zA-Z0-9\.]+/g);
|
|
477
|
+
// log.i('match', match)
|
|
478
|
+
match.forEach(e => {
|
|
479
|
+
let c = e.replace('\/:', '');
|
|
480
|
+
// log.i('c', c)
|
|
481
|
+
if (regexisPath.test(c)) {
|
|
482
|
+
url = url.replace(e, `/${_.get(params, c)}`);
|
|
483
|
+
}
|
|
484
|
+
else {
|
|
485
|
+
url = url.replace(e, `/${params[c]}`);
|
|
486
|
+
}
|
|
487
|
+
// log.i('prog url', url)
|
|
488
|
+
});
|
|
489
|
+
return url;
|
|
490
|
+
}
|
|
491
|
+
let nestedParams = url.match(/[a-zA-Z0-9]+\/:[a-zA-Z0-9\.]+/g);
|
|
492
|
+
if (!nestedParams || (Array.isArray(nestedParams) && nestedParams.length === 0))
|
|
493
|
+
return url;
|
|
494
|
+
// check alone params
|
|
495
|
+
if (!slash.end)
|
|
496
|
+
url = `${url}/`;
|
|
497
|
+
let addUndefinedForAlone = (!/:[a-zA-Z0-9\.]+\/$/g.test(url) && /[a-zA-Z0-9]+\/$/g.test(url));
|
|
498
|
+
let replace = (nestedParams.length > 1 ? nestedParams.join('\/') : nestedParams[0]) +
|
|
499
|
+
(addUndefinedForAlone ? '\/' + url.match(/[a-zA-Z0-9]+\/$/g)[0] : '\/');
|
|
500
|
+
let beginHref = url.replace(replace, '');
|
|
501
|
+
if (addUndefinedForAlone) {
|
|
502
|
+
url = url.replace(/\/$/g, '/:undefined');
|
|
503
|
+
nestedParams = url.match(/[a-zA-Z0-9]+\/:[a-zA-Z0-9\.]+/g);
|
|
504
|
+
url = cutUrlModel(params, nestedParams, []);
|
|
505
|
+
}
|
|
506
|
+
else {
|
|
507
|
+
url = cutUrlModel(params, nestedParams, []);
|
|
508
|
+
}
|
|
509
|
+
url = beginHref + url;
|
|
510
|
+
if (url.charAt(url.length - 1) !== '/' && slash.end)
|
|
511
|
+
url = `${url}/`;
|
|
512
|
+
if (url.charAt(0) !== '\/' && slash.start)
|
|
513
|
+
url = `/${url}`;
|
|
514
|
+
return url;
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Get query params from url, like 'ex' in /api/books?ex=value
|
|
518
|
+
*/
|
|
519
|
+
function decodeUrl(url) {
|
|
520
|
+
let regex = /[?&]([^=#]+)=([^&#]*)/g, params = {}, match;
|
|
521
|
+
while (match = regex.exec(url)) {
|
|
522
|
+
params[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
|
|
523
|
+
}
|
|
524
|
+
let paramsObject = params;
|
|
525
|
+
for (let p in paramsObject) {
|
|
526
|
+
if (paramsObject[p] === void 0) {
|
|
527
|
+
delete paramsObject[p];
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
if (paramsObject.hasOwnProperty(p)) {
|
|
531
|
+
// chcek if property is number
|
|
532
|
+
let n = Number(params[p]);
|
|
533
|
+
if (!isNaN(n)) {
|
|
534
|
+
params[p] = n;
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
if (typeof params[p] === 'string') {
|
|
538
|
+
// check if property is object
|
|
539
|
+
let json;
|
|
540
|
+
try {
|
|
541
|
+
json = JSON.parse(params[p]);
|
|
542
|
+
}
|
|
543
|
+
catch (error) { }
|
|
544
|
+
if (json !== void 0) {
|
|
545
|
+
params[p] = json;
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
// chcek if property value is like regular rexpression
|
|
549
|
+
// let regexExpression;
|
|
550
|
+
// try {
|
|
551
|
+
// regexExpression = new RegExp(params[p]);
|
|
552
|
+
// } catch (e) { }
|
|
553
|
+
// if (regexExpression !== undefined) params[p] = regexExpression;
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
return params;
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* Create query params string for url
|
|
561
|
+
*
|
|
562
|
+
* @export
|
|
563
|
+
* @param {UrlParams[]} params
|
|
564
|
+
* @returns {string}
|
|
565
|
+
*/
|
|
566
|
+
function getParamsUrl(params, doNotSerialize = false) {
|
|
567
|
+
let urlparts = [];
|
|
568
|
+
if (!params)
|
|
569
|
+
return '';
|
|
570
|
+
if (!(params instanceof Array))
|
|
571
|
+
return '';
|
|
572
|
+
if (params.length === 0)
|
|
573
|
+
return '';
|
|
574
|
+
params.forEach(urlparam => {
|
|
575
|
+
if (JSON.stringify(urlparam) !== '{}') {
|
|
576
|
+
let parameters = [];
|
|
577
|
+
let paramObject = urlparam;
|
|
578
|
+
for (let p in paramObject) {
|
|
579
|
+
if (paramObject[p] === void 0)
|
|
580
|
+
delete paramObject[p];
|
|
581
|
+
if (paramObject.hasOwnProperty(p) && typeof p === 'string' && p !== 'regex' && !(paramObject[p] instanceof RegExp)) {
|
|
582
|
+
if (p.length > 0 && p[0] === '/') {
|
|
583
|
+
let newName = p.slice(1, p.length - 1);
|
|
584
|
+
urlparam[newName] = urlparam[p];
|
|
585
|
+
urlparam[p] = void 0;
|
|
586
|
+
p = newName;
|
|
587
|
+
}
|
|
588
|
+
if (p.length > 0 && p[p.length - 1] === '/') {
|
|
589
|
+
let newName = p.slice(0, p.length - 2);
|
|
590
|
+
urlparam[newName] = urlparam[p];
|
|
591
|
+
urlparam[p] = void 0;
|
|
592
|
+
p = newName;
|
|
593
|
+
}
|
|
594
|
+
let v = urlparam[p];
|
|
595
|
+
if (v instanceof Object) {
|
|
596
|
+
urlparam[p] = JSON.stringify(urlparam[p]);
|
|
597
|
+
}
|
|
598
|
+
urlparam[p] = doNotSerialize ? urlparam[p] : encodeURIComponent(urlparam[p]);
|
|
599
|
+
if (urlparam.regex !== void 0 && urlparam.regex instanceof RegExp) {
|
|
600
|
+
if (!urlparam.regex.test(urlparam[p])) {
|
|
601
|
+
console.warn(`Data: ${urlparam[p]} incostistent with regex ${urlparam.regex.source}`);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
parameters.push(`${p}=${urlparam[p]}`);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
urlparts.push(parameters.join('&'));
|
|
608
|
+
}
|
|
609
|
+
});
|
|
610
|
+
let join = urlparts.join().trim();
|
|
611
|
+
if (join.trim() === '')
|
|
612
|
+
return '';
|
|
613
|
+
return `?${urlparts.join('&')}`;
|
|
614
|
+
}
|
|
615
|
+
function transform(o) {
|
|
616
|
+
if (typeof o === 'object') {
|
|
617
|
+
return encodeURIComponent(JSON.stringify(o));
|
|
618
|
+
}
|
|
619
|
+
return o;
|
|
620
|
+
}
|
|
621
|
+
function prepareUrlOldWay(params) {
|
|
622
|
+
if (!params)
|
|
623
|
+
return this.endpoint;
|
|
624
|
+
if (typeof params === 'object') {
|
|
625
|
+
params = transform(params);
|
|
626
|
+
}
|
|
627
|
+
return this.endpoint + '/' + params;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// Optional helper for passing around context (browser/client)
|
|
631
|
+
// === Backend handler (last in chain) ===
|
|
632
|
+
class AxiosBackendHandler {
|
|
633
|
+
handle(req) {
|
|
634
|
+
// axios returns a Promise; wrap as Observable
|
|
635
|
+
return from(axios.request(req));
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
// === Chain builder (request: forward order, response: reverse order) ===
|
|
639
|
+
const buildInterceptorChain = (interceptors, backend) => {
|
|
640
|
+
return interceptors.reduceRight((next, interceptor) => ({
|
|
641
|
+
handle: req => interceptor.intercept({ req, next }),
|
|
642
|
+
}), backend);
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
/* */
|
|
646
|
+
class RestCommonHttpResponseWrapper {
|
|
647
|
+
}
|
|
648
|
+
class RestResponseWrapper extends RestCommonHttpResponseWrapper {
|
|
649
|
+
}
|
|
650
|
+
class RestErrorResponseWrapper extends RestCommonHttpResponseWrapper {
|
|
651
|
+
}
|
|
652
|
+
// const log = Log.create('rest namespace', Level.__NOTHING)
|
|
653
|
+
var Models;
|
|
654
|
+
(function (Models) {
|
|
655
|
+
Models.MethodConfig = Models$1.MethodConfig;
|
|
656
|
+
Models.ClassConfig = Models$1.ClassConfig;
|
|
657
|
+
Models.ParamConfig = Models$1.ParamConfig;
|
|
658
|
+
[];
|
|
659
|
+
class BaseBody {
|
|
660
|
+
toJSON(data, opt) {
|
|
661
|
+
opt = opt || { isJSONArray: false };
|
|
662
|
+
let r = opt.isJSONArray ? [] : {};
|
|
663
|
+
if (typeof data === 'string') {
|
|
664
|
+
try {
|
|
665
|
+
let parsed = JSON.parse(data);
|
|
666
|
+
if (typeof parsed === 'string' && parsed.trim().startsWith('{')) {
|
|
667
|
+
parsed = JSON.parse(parsed);
|
|
668
|
+
}
|
|
669
|
+
if (opt.parsingError && parsed[CoreModels.TaonHttpErrorCustomProp]) {
|
|
670
|
+
return _.merge(new RestErrorResponseWrapper(), parsed);
|
|
671
|
+
}
|
|
672
|
+
return parsed;
|
|
673
|
+
}
|
|
674
|
+
catch (e) { }
|
|
675
|
+
}
|
|
676
|
+
else if (typeof data === 'object') {
|
|
677
|
+
return data;
|
|
678
|
+
}
|
|
679
|
+
return r;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
Models.BaseBody = BaseBody;
|
|
683
|
+
class HttpBody extends BaseBody {
|
|
684
|
+
constructor(responseText, isArray = false, entity, circular) {
|
|
685
|
+
super();
|
|
686
|
+
this.responseText = responseText;
|
|
687
|
+
this.isArray = isArray;
|
|
688
|
+
this.entity = entity;
|
|
689
|
+
this.circular = circular;
|
|
690
|
+
}
|
|
691
|
+
get blob() {
|
|
692
|
+
return this.responseText;
|
|
693
|
+
}
|
|
694
|
+
get booleanValue() {
|
|
695
|
+
if (!Helpers$1.isBlob(this.responseText)) {
|
|
696
|
+
return ['ok', 'true'].includes(this.responseText?.trim());
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
get numericValue() {
|
|
700
|
+
if (!Helpers$1.isBlob(this.responseText)) {
|
|
701
|
+
return Number(this.responseText?.trim());
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
get rawJson() {
|
|
705
|
+
if (!Helpers$1.isBlob(this.responseText)) {
|
|
706
|
+
let res = this.toJSON(this.responseText, { isJSONArray: this.isArray });
|
|
707
|
+
if (this.circular && Array.isArray(this.circular)) {
|
|
708
|
+
res = JSON10.parse(JSON.stringify(res), this.circular);
|
|
709
|
+
}
|
|
710
|
+
return res;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
get json() {
|
|
714
|
+
const isBlob = Helpers$1.isBlob(this.responseText);
|
|
715
|
+
if (isBlob) {
|
|
716
|
+
return void 0;
|
|
717
|
+
}
|
|
718
|
+
if (this.entity && typeof this.entity === 'function') {
|
|
719
|
+
return this.entity(); // @LAST
|
|
720
|
+
}
|
|
721
|
+
if (this.entity && typeof this.entity === 'object') {
|
|
722
|
+
const json = this.toJSON(this.responseText, {
|
|
723
|
+
isJSONArray: this.isArray,
|
|
724
|
+
});
|
|
725
|
+
return Mapping.encode(json, this.entity, this.circular);
|
|
726
|
+
}
|
|
727
|
+
let res = this.toJSON(this.responseText, { isJSONArray: this.isArray });
|
|
728
|
+
if (this.circular && Array.isArray(this.circular)) {
|
|
729
|
+
res = JSON10.parse(JSON.stringify(res), this.circular);
|
|
730
|
+
}
|
|
731
|
+
return res;
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* undefined when blob
|
|
735
|
+
*/
|
|
736
|
+
get text() {
|
|
737
|
+
if (!Helpers$1.isBlob(this.responseText)) {
|
|
738
|
+
return this.responseText
|
|
739
|
+
.replace(/^\"/, '')
|
|
740
|
+
.replace(/\"$/, '');
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
Models.HttpBody = HttpBody;
|
|
745
|
+
class ErrorBody extends BaseBody {
|
|
746
|
+
constructor(data) {
|
|
747
|
+
super();
|
|
748
|
+
this.data = data;
|
|
749
|
+
}
|
|
750
|
+
get json() {
|
|
751
|
+
return this.toJSON(this.data, { parsingError: true });
|
|
752
|
+
}
|
|
753
|
+
get text() {
|
|
754
|
+
return this.data;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
Models.ErrorBody = ErrorBody;
|
|
758
|
+
class BaseResponse {
|
|
759
|
+
static { this.cookies = Cookie.Instance; }
|
|
760
|
+
get cookies() {
|
|
761
|
+
return BaseResponse.cookies;
|
|
762
|
+
}
|
|
763
|
+
constructor(responseText, headers, statusCode, isArray = false) {
|
|
764
|
+
this.responseText = responseText;
|
|
765
|
+
this.headers = headers;
|
|
766
|
+
this.statusCode = statusCode;
|
|
767
|
+
this.isArray = isArray;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
Models.BaseResponse = BaseResponse;
|
|
771
|
+
class HttpResponse extends BaseResponse {
|
|
772
|
+
// public readonly TOTAL_COUNT_HEADER = 'X-Total-Count'.toLowerCase();
|
|
773
|
+
// public get totalElements(): number {
|
|
774
|
+
// return Number(this.headers.get(this.TOTAL_COUNT_HEADER));
|
|
775
|
+
// }
|
|
776
|
+
constructor(sourceRequest, responseText, headers, statusCode, entity, circular, jobid, isArray = false) {
|
|
777
|
+
// console.log({
|
|
778
|
+
// sourceRequest, responseText, headers, statusCode, entity, circular, jobid, isArray
|
|
779
|
+
// })
|
|
780
|
+
super(responseText, headers, statusCode, isArray);
|
|
781
|
+
this.sourceRequest = sourceRequest;
|
|
782
|
+
this.responseText = responseText;
|
|
783
|
+
this.headers = headers;
|
|
784
|
+
this.statusCode = statusCode;
|
|
785
|
+
this.entity = entity;
|
|
786
|
+
this.circular = circular;
|
|
787
|
+
this.jobid = jobid;
|
|
788
|
+
this.isArray = isArray;
|
|
789
|
+
this.init();
|
|
790
|
+
}
|
|
791
|
+
init() {
|
|
792
|
+
if (typeof this.entity === 'string') {
|
|
793
|
+
// const headerWithMapping = headers.get(entity);
|
|
794
|
+
let entityJSON = this.headers?.getAll(this.entity);
|
|
795
|
+
if (!!entityJSON) {
|
|
796
|
+
this.entity = JSON.parse(entityJSON.join());
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
if (typeof this.circular === 'string') {
|
|
800
|
+
// const headerWithMapping = headers.get(circular);
|
|
801
|
+
let circuralJSON = this.headers?.getAll(this.circular);
|
|
802
|
+
if (!!circuralJSON) {
|
|
803
|
+
this.circular = JSON.parse(circuralJSON.join());
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
this.body = new HttpBody(this.responseText, this.isArray, this.entity, this.circular);
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
Models.HttpResponse = HttpResponse;
|
|
810
|
+
/* */
|
|
811
|
+
/* */
|
|
812
|
+
/* */
|
|
813
|
+
/* */
|
|
814
|
+
/* */
|
|
815
|
+
/* */
|
|
816
|
+
})(Models || (Models = {}));
|
|
817
|
+
class HttpResponseError extends Models.BaseResponse {
|
|
818
|
+
// public tryRecconect() {
|
|
819
|
+
// }
|
|
820
|
+
constructor(message, responseText, headers, statusCode, jobid, sourceRequest) {
|
|
821
|
+
super(responseText, headers, statusCode);
|
|
822
|
+
this.message = message;
|
|
823
|
+
this.jobid = jobid;
|
|
824
|
+
this.sourceRequest = sourceRequest;
|
|
825
|
+
this.body = new Models.ErrorBody(responseText);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
class RestHeaders {
|
|
830
|
+
static from(headers) {
|
|
831
|
+
if (!headers) {
|
|
832
|
+
return void 0;
|
|
833
|
+
}
|
|
834
|
+
return new RestHeaders(headers);
|
|
835
|
+
}
|
|
836
|
+
constructor(headers) {
|
|
837
|
+
/** @internal header names are lower case */
|
|
838
|
+
this._headers = new Map();
|
|
839
|
+
/** @internal map lower case names to actual names */
|
|
840
|
+
this._normalizedNames = new Map();
|
|
841
|
+
if (headers instanceof RestHeaders) {
|
|
842
|
+
headers.forEach((values, name) => {
|
|
843
|
+
values.forEach(value => this.set(name, value));
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
else {
|
|
847
|
+
Object.keys(headers).forEach((name) => {
|
|
848
|
+
const values = (Array.isArray(headers[name]) ? headers[name] : [headers[name]]);
|
|
849
|
+
this.delete(name);
|
|
850
|
+
values.forEach(value => this.set(name, value));
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Returns a new RestHeaders instance from the given DOMString of Response RestHeaders
|
|
856
|
+
*/
|
|
857
|
+
static fromResponseHeaderString(headersString) {
|
|
858
|
+
const headers = new RestHeaders();
|
|
859
|
+
// console.log({
|
|
860
|
+
// headersString
|
|
861
|
+
// })
|
|
862
|
+
headersString.split('\n').forEach(line => {
|
|
863
|
+
const index = line.indexOf(':');
|
|
864
|
+
if (index > 0) {
|
|
865
|
+
const name = line.slice(0, index);
|
|
866
|
+
const value = line.slice(index + 1).trim();
|
|
867
|
+
headers.set(name, value);
|
|
868
|
+
}
|
|
869
|
+
});
|
|
870
|
+
return headers;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Appends a header to existing list of header values for a given header name.
|
|
874
|
+
*/
|
|
875
|
+
append(name, value) {
|
|
876
|
+
const values = this.getAll(name);
|
|
877
|
+
if (values === null) {
|
|
878
|
+
this.set(name, value);
|
|
879
|
+
}
|
|
880
|
+
else {
|
|
881
|
+
values.push(value);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Deletes all header values for the given name.
|
|
886
|
+
*/
|
|
887
|
+
delete(name) {
|
|
888
|
+
const lcName = name.toLowerCase();
|
|
889
|
+
this._normalizedNames.delete(lcName);
|
|
890
|
+
this._headers.delete(lcName);
|
|
891
|
+
}
|
|
892
|
+
forEach(fn) {
|
|
893
|
+
this._headers.forEach((values, lcName) => fn(values, this._normalizedNames.get(lcName), this._headers));
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* Returns first header that matches given name.
|
|
897
|
+
*/
|
|
898
|
+
get(name) {
|
|
899
|
+
const values = this.getAll(name);
|
|
900
|
+
if (values === null) {
|
|
901
|
+
return null;
|
|
902
|
+
}
|
|
903
|
+
return values.length > 0 ? values[0] : null;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Checks for existence of header by given name.
|
|
907
|
+
*/
|
|
908
|
+
has(name) { return this._headers.has(name.toLowerCase()); }
|
|
909
|
+
/**
|
|
910
|
+
* Returns the names of the headers
|
|
911
|
+
*/
|
|
912
|
+
keys() { return Array.from(this._normalizedNames.values()); }
|
|
913
|
+
/**
|
|
914
|
+
* Sets or overrides header value for given name.
|
|
915
|
+
*/
|
|
916
|
+
set(name, value) {
|
|
917
|
+
if (Array.isArray(value)) {
|
|
918
|
+
if (value.length) {
|
|
919
|
+
this._headers.set(name.toLowerCase(), [value.join(',')]);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
else {
|
|
923
|
+
this._headers.set(name.toLowerCase(), [value]);
|
|
924
|
+
}
|
|
925
|
+
this.mayBeSetNormalizedName(name);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Returns values of all headers.
|
|
929
|
+
*/
|
|
930
|
+
values() { return Array.from(this._headers.values()); }
|
|
931
|
+
/**
|
|
932
|
+
* Returns string of all headers.
|
|
933
|
+
*/
|
|
934
|
+
// TODO(vicb): returns {[name: string]: string[]}
|
|
935
|
+
toJSON() {
|
|
936
|
+
const serialized = {};
|
|
937
|
+
if (!this._headers) {
|
|
938
|
+
// debugger
|
|
939
|
+
}
|
|
940
|
+
// console.log('serializing headers',this._headers)
|
|
941
|
+
this._headers.forEach((values, name) => {
|
|
942
|
+
const split = [];
|
|
943
|
+
values.forEach(v => split.push(...v.split(',')));
|
|
944
|
+
// console.log({
|
|
945
|
+
// values
|
|
946
|
+
// })
|
|
947
|
+
// values.forEach(v => split.push(...(v ? v : '').split(',')));
|
|
948
|
+
serialized[this._normalizedNames.get(name)] = split;
|
|
949
|
+
});
|
|
950
|
+
return serialized;
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* Returns list of header values for a given name.
|
|
954
|
+
*/
|
|
955
|
+
getAll(name) {
|
|
956
|
+
return this.has(name) ? this._headers.get(name.toLowerCase()) : null;
|
|
957
|
+
}
|
|
958
|
+
mayBeSetNormalizedName(name) {
|
|
959
|
+
const lcName = name.toLowerCase();
|
|
960
|
+
if (!this._normalizedNames.has(lcName)) {
|
|
961
|
+
this._normalizedNames.set(lcName, name);
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
//#region imports
|
|
967
|
+
//#endregion
|
|
968
|
+
// const log = Log.create('[ng2-rest] rest-request', Level.__NOTHING);
|
|
969
|
+
/**
|
|
970
|
+
* TODO refactor this (remove jobid)
|
|
971
|
+
*/
|
|
972
|
+
const jobIDkey = 'jobID';
|
|
973
|
+
const customObs = 'customObs';
|
|
974
|
+
const cancelFn = 'cancelFn';
|
|
975
|
+
const isCanceled = 'isCanceled';
|
|
976
|
+
//#region mock request
|
|
977
|
+
//#endregion
|
|
978
|
+
class RestRequest {
|
|
979
|
+
constructor() {
|
|
980
|
+
this.subjectInuUse = {};
|
|
981
|
+
this.meta = {};
|
|
982
|
+
//#endregion
|
|
983
|
+
/**
|
|
984
|
+
* key is interceptorName (just to identify who is intercepting)
|
|
985
|
+
*/
|
|
986
|
+
this.interceptors = new Map();
|
|
987
|
+
/**
|
|
988
|
+
* key is a joined string METHOD-expressPath.
|
|
989
|
+
* Example `GET-/api/users`
|
|
990
|
+
*/
|
|
991
|
+
this.methodsInterceptors = new Map();
|
|
992
|
+
//#endregion
|
|
993
|
+
this.replaySubjects = {};
|
|
994
|
+
}
|
|
995
|
+
//#region fields
|
|
996
|
+
static { this.jobId = 0; }
|
|
997
|
+
handlerResult(options, sourceRequest) {
|
|
998
|
+
if (_.isUndefined(options)) {
|
|
999
|
+
options = {};
|
|
1000
|
+
}
|
|
1001
|
+
// log.d(`HANDLE RESULT (jobid:${options.jobid}) ${sourceRequest.url}`);
|
|
1002
|
+
const { res, jobid, isArray, method } = options;
|
|
1003
|
+
if (typeof res !== 'object') {
|
|
1004
|
+
throw new Error('No resposnse for request. ');
|
|
1005
|
+
}
|
|
1006
|
+
if (Helpers$1.isBrowser) {
|
|
1007
|
+
res.headers = RestHeaders.from(res.headers);
|
|
1008
|
+
}
|
|
1009
|
+
// error no internet
|
|
1010
|
+
if (res.error) {
|
|
1011
|
+
this.subjectInuUse[jobid].error(new HttpResponseError(res.error, res.data, res.headers, res.code, jobid, sourceRequest));
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
const entity = this.meta[jobid].entity;
|
|
1015
|
+
const circular = this.meta[jobid].circular;
|
|
1016
|
+
const success = Resource['_listenSuccess'];
|
|
1017
|
+
const reqResp = new Models.HttpResponse(sourceRequest, res.data, res.headers, res.code, entity, circular, jobid, isArray);
|
|
1018
|
+
success.next(reqResp);
|
|
1019
|
+
this.subjectInuUse[jobid].next(reqResp);
|
|
1020
|
+
this.meta[jobid] = void 0;
|
|
1021
|
+
this.subjectInuUse[jobid].complete();
|
|
1022
|
+
}
|
|
1023
|
+
async req(url, method, headers, body, jobid, isArray = false, mockHttp, axiosOptions) {
|
|
1024
|
+
const CancelToken = axios.CancelToken;
|
|
1025
|
+
const source = CancelToken.source();
|
|
1026
|
+
this.subjectInuUse[jobid][cancelFn] = source.cancel;
|
|
1027
|
+
var response;
|
|
1028
|
+
if (mockHttp) {
|
|
1029
|
+
if (typeof mockHttp === 'object') {
|
|
1030
|
+
response = {
|
|
1031
|
+
data: mockHttp.data,
|
|
1032
|
+
status: mockHttp.code,
|
|
1033
|
+
headers: mockHttp.headers,
|
|
1034
|
+
statusText: mockHttp.error,
|
|
1035
|
+
config: {},
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
else if (typeof mockHttp === 'function') {
|
|
1039
|
+
const r = mockHttp(url, method, headers, body);
|
|
1040
|
+
response = {
|
|
1041
|
+
data: r.data,
|
|
1042
|
+
status: r.code,
|
|
1043
|
+
headers: r.headers,
|
|
1044
|
+
statusText: r.error,
|
|
1045
|
+
config: {},
|
|
1046
|
+
};
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
const isFormData = CLASS.getNameFromObject(body) === 'FormData';
|
|
1050
|
+
const formData = isFormData ? body : void 0;
|
|
1051
|
+
/* */
|
|
1052
|
+
/* */
|
|
1053
|
+
/* */
|
|
1054
|
+
/* */
|
|
1055
|
+
/* */
|
|
1056
|
+
/* */
|
|
1057
|
+
/* */
|
|
1058
|
+
/* */
|
|
1059
|
+
const headersJson = headers.toJSON();
|
|
1060
|
+
const responseType = headersJson.responsetypeaxios
|
|
1061
|
+
? headersJson.responsetypeaxios
|
|
1062
|
+
: 'text';
|
|
1063
|
+
try {
|
|
1064
|
+
if (!response) {
|
|
1065
|
+
/* */
|
|
1066
|
+
/* */
|
|
1067
|
+
/* */
|
|
1068
|
+
/* */
|
|
1069
|
+
// console.log('headers axios:', headers.toJSON())
|
|
1070
|
+
// console.log({ responseType, headersJson, body, method, url })
|
|
1071
|
+
let axiosConfig = {
|
|
1072
|
+
url,
|
|
1073
|
+
method,
|
|
1074
|
+
data: body,
|
|
1075
|
+
responseType,
|
|
1076
|
+
headers: headersJson,
|
|
1077
|
+
cancelToken: source.token,
|
|
1078
|
+
...(axiosOptions || {}), // merge with axiosOptions
|
|
1079
|
+
// withCredentials: true, // this can be done manually
|
|
1080
|
+
};
|
|
1081
|
+
if (isFormData) {
|
|
1082
|
+
axiosConfig.maxBodyLength = Infinity;
|
|
1083
|
+
}
|
|
1084
|
+
// console.log('AXIOS CONFIG', axiosConfig);
|
|
1085
|
+
const uri = new URL(url);
|
|
1086
|
+
const backend = new AxiosBackendHandler();
|
|
1087
|
+
const globalInterceptors = Array.from(this.interceptors.entries()).map(([_, interceptor]) => interceptor);
|
|
1088
|
+
const methodInterceptors = Array.from(this.methodsInterceptors.entries())
|
|
1089
|
+
.filter(([key]) => {
|
|
1090
|
+
const ending = `-${method?.toUpperCase()}-${uri.pathname}`;
|
|
1091
|
+
return key.endsWith(ending);
|
|
1092
|
+
})
|
|
1093
|
+
.map(([_, interceptor]) => interceptor);
|
|
1094
|
+
// console.log(
|
|
1095
|
+
// `for ${uri.pathname} global ${globalInterceptors.length} method: ${methodInterceptors.length}`,
|
|
1096
|
+
// );
|
|
1097
|
+
const allInterceptors = [...globalInterceptors, ...methodInterceptors];
|
|
1098
|
+
const handler = buildInterceptorChain(allInterceptors, backend);
|
|
1099
|
+
response = await firstValueFrom(handler.handle(axiosConfig));
|
|
1100
|
+
// log.d(`after response of jobid: ${jobid}`);
|
|
1101
|
+
}
|
|
1102
|
+
// console.log('AXIOS RESPONES', response)
|
|
1103
|
+
if (this.subjectInuUse[jobid][isCanceled]) {
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
// handle normal request
|
|
1107
|
+
this.handlerResult({
|
|
1108
|
+
res: {
|
|
1109
|
+
code: response.status,
|
|
1110
|
+
data: response.data,
|
|
1111
|
+
isArray,
|
|
1112
|
+
jobid,
|
|
1113
|
+
headers: RestHeaders.from(response.headers),
|
|
1114
|
+
},
|
|
1115
|
+
method,
|
|
1116
|
+
jobid,
|
|
1117
|
+
isArray,
|
|
1118
|
+
}, {
|
|
1119
|
+
url,
|
|
1120
|
+
body,
|
|
1121
|
+
method,
|
|
1122
|
+
isArray,
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
catch (catchedError) {
|
|
1126
|
+
if (this.subjectInuUse[jobid][isCanceled]) {
|
|
1127
|
+
return;
|
|
1128
|
+
}
|
|
1129
|
+
// console.log('ERROR RESPONESE catchedError typeof ', typeof catchedError)
|
|
1130
|
+
// console.log('ERROR RESPONESE catchedError', catchedError)
|
|
1131
|
+
if (typeof catchedError === 'object' &&
|
|
1132
|
+
catchedError.response &&
|
|
1133
|
+
catchedError.response.data) {
|
|
1134
|
+
const err = catchedError.response.data;
|
|
1135
|
+
const msg = catchedError.response.data.message || '';
|
|
1136
|
+
// console.log({
|
|
1137
|
+
// 'err.stack': err?.stack
|
|
1138
|
+
// })
|
|
1139
|
+
let stack = (err.stack || '').split('\n');
|
|
1140
|
+
const errObs = Resource['_listenErrors'];
|
|
1141
|
+
errObs.next({
|
|
1142
|
+
msg,
|
|
1143
|
+
stack,
|
|
1144
|
+
data: catchedError.response.data,
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
const error = catchedError && catchedError.response
|
|
1148
|
+
? `[${catchedError.response.statusText}]: `
|
|
1149
|
+
: '';
|
|
1150
|
+
// handle error request
|
|
1151
|
+
this.handlerResult({
|
|
1152
|
+
res: {
|
|
1153
|
+
code: catchedError && catchedError.response
|
|
1154
|
+
? catchedError.response.status
|
|
1155
|
+
: void 0,
|
|
1156
|
+
error: `${error}${catchedError.message}`,
|
|
1157
|
+
data: catchedError && catchedError.response
|
|
1158
|
+
? JSON.stringify(catchedError.response.data)
|
|
1159
|
+
: void 0,
|
|
1160
|
+
isArray,
|
|
1161
|
+
jobid,
|
|
1162
|
+
headers: RestHeaders.from(catchedError &&
|
|
1163
|
+
catchedError.response &&
|
|
1164
|
+
catchedError.response.headers),
|
|
1165
|
+
},
|
|
1166
|
+
method,
|
|
1167
|
+
jobid,
|
|
1168
|
+
isArray,
|
|
1169
|
+
}, {
|
|
1170
|
+
url,
|
|
1171
|
+
body,
|
|
1172
|
+
isArray,
|
|
1173
|
+
method,
|
|
1174
|
+
});
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
getReplay(method, meta, onlyGetLastReplayForMethod) {
|
|
1178
|
+
let replay;
|
|
1179
|
+
//#region prevent empty tree
|
|
1180
|
+
if (_.isUndefined(this.replaySubjects[meta.endpoint])) {
|
|
1181
|
+
// log.i(`(${meta.endpoint}) `);
|
|
1182
|
+
this.replaySubjects[meta.endpoint] = {};
|
|
1183
|
+
}
|
|
1184
|
+
if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path])) {
|
|
1185
|
+
// log.i(`(${meta.endpoint})(${meta.path}) `);
|
|
1186
|
+
this.replaySubjects[meta.endpoint][meta.path] = {};
|
|
1187
|
+
}
|
|
1188
|
+
if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path][method])) {
|
|
1189
|
+
// log.i(`(${meta.endpoint})(${meta.path}) `);
|
|
1190
|
+
this.replaySubjects[meta.endpoint][meta.path][method] = {};
|
|
1191
|
+
}
|
|
1192
|
+
//#endregion
|
|
1193
|
+
const objectIDToCreateOrLast = Object.keys(this.replaySubjects[meta.endpoint][meta.path][method]).length + (onlyGetLastReplayForMethod ? 0 : 1);
|
|
1194
|
+
if (onlyGetLastReplayForMethod && objectIDToCreateOrLast === 0) {
|
|
1195
|
+
return replay;
|
|
1196
|
+
}
|
|
1197
|
+
if (_.isUndefined(this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast])) {
|
|
1198
|
+
// log.i(`(${meta.endpoint})(${meta.path})(${method}) `);
|
|
1199
|
+
this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast] = {
|
|
1200
|
+
subject: new Subject(),
|
|
1201
|
+
data: void 0,
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
replay =
|
|
1205
|
+
this.replaySubjects[meta.endpoint][meta.path][method][objectIDToCreateOrLast];
|
|
1206
|
+
if (!_.isNumber(replay.id)) {
|
|
1207
|
+
if (RestRequest.jobId === Number.MAX_SAFE_INTEGER) {
|
|
1208
|
+
RestRequest.jobId = 0;
|
|
1209
|
+
}
|
|
1210
|
+
const jobid = RestRequest.jobId++;
|
|
1211
|
+
replay.id = jobid;
|
|
1212
|
+
const subject = replay.subject;
|
|
1213
|
+
subject[jobIDkey] = jobid; // modify internal rxjs subject obj
|
|
1214
|
+
this.meta[jobid] = meta;
|
|
1215
|
+
this.subjectInuUse[jobid] = subject;
|
|
1216
|
+
this.subjectInuUse[jobid][customObs] = new Observable(observer => {
|
|
1217
|
+
// observer.remove(() => {
|
|
1218
|
+
// });
|
|
1219
|
+
observer.add(() => {
|
|
1220
|
+
// console.log(`cancel observable job${jobid}`)
|
|
1221
|
+
if (!this.subjectInuUse[jobid][isCanceled]) {
|
|
1222
|
+
this.subjectInuUse[jobid][isCanceled] = true;
|
|
1223
|
+
if (typeof this.subjectInuUse[jobid][cancelFn] === 'function') {
|
|
1224
|
+
this.subjectInuUse[jobid][cancelFn]('[ng2-rest] on purpose canceled http request');
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
else {
|
|
1228
|
+
// console.log(`somehow second time cancel ${jobid}`)
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
const sub = subject.subscribe({
|
|
1232
|
+
next: a => observer.next(a),
|
|
1233
|
+
error: a => observer.error(a),
|
|
1234
|
+
complete: () => {
|
|
1235
|
+
setTimeout(() => {
|
|
1236
|
+
sub.unsubscribe();
|
|
1237
|
+
observer.complete();
|
|
1238
|
+
});
|
|
1239
|
+
},
|
|
1240
|
+
});
|
|
1241
|
+
});
|
|
1242
|
+
//#region DISPOSE @UNCOMMENT AFTER TESTS
|
|
1243
|
+
// if (objectIDToCreateOrLast > 2) {
|
|
1244
|
+
// const oldReq: Models.ReplayData = this.replaySubjects[meta.endpoint][meta.path][method][(objectIDToCreateOrLast - 2)];
|
|
1245
|
+
// if (_.isUndefined(this.meta[oldReq.id])) {
|
|
1246
|
+
// // cant delete this - for counter purpose
|
|
1247
|
+
// this.replaySubjects[meta.endpoint][meta.path][method][(objectIDToCreateOrLast - 2)] = {};
|
|
1248
|
+
// delete this.subjectInuUse[oldReq.id];
|
|
1249
|
+
// delete this.meta[oldReq.id];
|
|
1250
|
+
// }
|
|
1251
|
+
// }
|
|
1252
|
+
//#endregion
|
|
1253
|
+
}
|
|
1254
|
+
return replay;
|
|
1255
|
+
}
|
|
1256
|
+
//#region http methods
|
|
1257
|
+
generalReq(method, url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1258
|
+
const replay = this.getReplay(method, meta, false);
|
|
1259
|
+
replay.data = { url, body, headers, isArray };
|
|
1260
|
+
((pthis, purl, pmethod, pheaders, pbody, pid, pisArray, pmockHttp, axiosOpt) => {
|
|
1261
|
+
// log.d(`for ${purl} jobid ${pid}`);
|
|
1262
|
+
setTimeout(() => pthis.req(purl, pmethod, pheaders, pbody, pid, pisArray, pmockHttp, axiosOpt));
|
|
1263
|
+
})(this, url, method, headers, body, replay.id, isArray, mockHttp, axiosOptions);
|
|
1264
|
+
const resp = firstValueFrom(replay.subject[customObs]);
|
|
1265
|
+
resp.observable = replay.subject[customObs];
|
|
1266
|
+
return resp;
|
|
1267
|
+
}
|
|
1268
|
+
get(url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1269
|
+
return this.generalReq('get', url, body, headers, meta, isArray, mockHttp, axiosOptions);
|
|
1270
|
+
}
|
|
1271
|
+
head(url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1272
|
+
return this.generalReq('head', url, body, headers, meta, isArray, mockHttp, axiosOptions);
|
|
1273
|
+
}
|
|
1274
|
+
delete(url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1275
|
+
return this.generalReq('delete', url, body, headers, meta, isArray, mockHttp, axiosOptions);
|
|
1276
|
+
}
|
|
1277
|
+
post(url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1278
|
+
return this.generalReq('post', url, body, headers, meta, isArray, mockHttp, axiosOptions);
|
|
1279
|
+
}
|
|
1280
|
+
put(url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1281
|
+
return this.generalReq('put', url, body, headers, meta, isArray, mockHttp, axiosOptions);
|
|
1282
|
+
}
|
|
1283
|
+
patch(url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1284
|
+
return this.generalReq('patch', url, body, headers, meta, isArray, mockHttp, axiosOptions);
|
|
1285
|
+
}
|
|
1286
|
+
jsonp(url, body, headers, meta, isArray, mockHttp, axiosOptions) {
|
|
1287
|
+
const method = 'jsonp';
|
|
1288
|
+
if (UtilsOs.isSSRMode) {
|
|
1289
|
+
const emptyStuff = Promise.resolve();
|
|
1290
|
+
emptyStuff.observable = new Observable();
|
|
1291
|
+
console.warn(`Cannot perform jsonp request in SSR mode`);
|
|
1292
|
+
return emptyStuff;
|
|
1293
|
+
}
|
|
1294
|
+
const replay = this.getReplay('jsonp', meta, false);
|
|
1295
|
+
const jobid = replay.id;
|
|
1296
|
+
setTimeout(() => {
|
|
1297
|
+
if (url.endsWith('/'))
|
|
1298
|
+
url = url.slice(0, url.length - 1);
|
|
1299
|
+
let num = Math.round(10000 * Math.random());
|
|
1300
|
+
let callbackMethodName = 'cb_' + num;
|
|
1301
|
+
let win = globalThis; // TODO not a good idea! @LAST
|
|
1302
|
+
win[callbackMethodName] = data => {
|
|
1303
|
+
// handle jsonp result data
|
|
1304
|
+
this.handlerResult({
|
|
1305
|
+
res: {
|
|
1306
|
+
data,
|
|
1307
|
+
isArray,
|
|
1308
|
+
},
|
|
1309
|
+
method,
|
|
1310
|
+
jobid,
|
|
1311
|
+
isArray,
|
|
1312
|
+
}, {
|
|
1313
|
+
url,
|
|
1314
|
+
body,
|
|
1315
|
+
isArray,
|
|
1316
|
+
method,
|
|
1317
|
+
});
|
|
1318
|
+
};
|
|
1319
|
+
let sc = document.createElement('script');
|
|
1320
|
+
sc.src = `${url}?callback=${callbackMethodName}`;
|
|
1321
|
+
document.body.appendChild(sc);
|
|
1322
|
+
document.body.removeChild(sc);
|
|
1323
|
+
});
|
|
1324
|
+
const resp = firstValueFrom(replay.subject[customObs]);
|
|
1325
|
+
resp.observable = replay.subject[customObs];
|
|
1326
|
+
return resp;
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
const CONTENT_TYPE = {
|
|
1331
|
+
APPLICATION_JSON: RestHeaders.from({
|
|
1332
|
+
'Content-Type': 'application/json',
|
|
1333
|
+
'Accept': 'application/json'
|
|
1334
|
+
}),
|
|
1335
|
+
APPLICATINO_VND_API_JSON: RestHeaders.from({
|
|
1336
|
+
'Content-Type': 'application/vnd.api+json',
|
|
1337
|
+
'Accept': 'application/vnd.api+json'
|
|
1338
|
+
}),
|
|
1339
|
+
};
|
|
1340
|
+
|
|
1341
|
+
//#region import
|
|
1342
|
+
// import { Log, Level } from 'ng2-logger/src';
|
|
1343
|
+
// const log = Log.create('rest.class', Level.__NOTHING)
|
|
1344
|
+
//#endregion
|
|
1345
|
+
class Rest {
|
|
1346
|
+
mock(mock) {
|
|
1347
|
+
if (typeof mock === 'function' || typeof mock === 'object') {
|
|
1348
|
+
this.mockHttp = mock;
|
|
1349
|
+
}
|
|
1350
|
+
else {
|
|
1351
|
+
throw `[ng2-rest]
|
|
1352
|
+
.model(...)
|
|
1353
|
+
.mock( < BAD MOCK DATA > )
|
|
1354
|
+
...
|
|
1355
|
+
`;
|
|
1356
|
+
}
|
|
1357
|
+
return this;
|
|
1358
|
+
}
|
|
1359
|
+
get endpoint() {
|
|
1360
|
+
let e = this.__meta_endpoint;
|
|
1361
|
+
if (this.restQueryParams !== void 0 &&
|
|
1362
|
+
this._endpointRest !== void 0 &&
|
|
1363
|
+
typeof this._endpointRest === 'string' &&
|
|
1364
|
+
this._endpointRest.trim() !== '')
|
|
1365
|
+
e = this._endpointRest;
|
|
1366
|
+
return e;
|
|
1367
|
+
}
|
|
1368
|
+
set __rest_endpoint(endpoint) {
|
|
1369
|
+
this._endpointRest = endpoint;
|
|
1370
|
+
if (endpoint === void 0) {
|
|
1371
|
+
this.restQueryParams = void 0;
|
|
1372
|
+
}
|
|
1373
|
+
else {
|
|
1374
|
+
this.restQueryParams = getRestParams(endpoint, this.__meta_endpoint);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
creatUrl(params, doNotSerializeParams = false) {
|
|
1378
|
+
return `${this.endpoint}${getParamsUrl(params, doNotSerializeParams)}`;
|
|
1379
|
+
}
|
|
1380
|
+
get headers() {
|
|
1381
|
+
return this._headers;
|
|
1382
|
+
}
|
|
1383
|
+
constructor(endpoint, request, meta, customContentType) {
|
|
1384
|
+
this.request = request;
|
|
1385
|
+
this.meta = meta;
|
|
1386
|
+
this.customContentType = customContentType;
|
|
1387
|
+
//#endregion
|
|
1388
|
+
//#region constructor
|
|
1389
|
+
this._headers = RestHeaders.from(CONTENT_TYPE.APPLICATION_JSON);
|
|
1390
|
+
//#endregion
|
|
1391
|
+
//#region http methods
|
|
1392
|
+
this.array = {
|
|
1393
|
+
get: (item, params = void 0, axiosOptions) => {
|
|
1394
|
+
return this.req('get', item, params, axiosOptions, true);
|
|
1395
|
+
},
|
|
1396
|
+
head: (item, params = void 0, axiosOptions) => {
|
|
1397
|
+
return this.req('head', item, params, axiosOptions, true);
|
|
1398
|
+
},
|
|
1399
|
+
post: (item, params, axiosOptions) => {
|
|
1400
|
+
return this.req('post', item, params, axiosOptions, true);
|
|
1401
|
+
},
|
|
1402
|
+
put: (item, params, axiosOptions) => {
|
|
1403
|
+
return this.req('put', item, params, axiosOptions, true);
|
|
1404
|
+
},
|
|
1405
|
+
patch: (item, params, axiosOptions) => {
|
|
1406
|
+
return this.req('patch', item, params, axiosOptions, true);
|
|
1407
|
+
},
|
|
1408
|
+
delete: (item, params, axiosOptions) => {
|
|
1409
|
+
return this.req('delete', item, params, axiosOptions, true);
|
|
1410
|
+
},
|
|
1411
|
+
jsonp: (item, params, axiosOptions) => {
|
|
1412
|
+
return this.req('jsonp', item, params, axiosOptions, true);
|
|
1413
|
+
},
|
|
1414
|
+
};
|
|
1415
|
+
this.__meta_endpoint = endpoint;
|
|
1416
|
+
}
|
|
1417
|
+
//#endregion
|
|
1418
|
+
//#region req
|
|
1419
|
+
req(method, requestBody, params, axiosOptions, isArray = false) {
|
|
1420
|
+
axiosOptions = axiosOptions || {};
|
|
1421
|
+
const modelUrl = this.creatUrl(params, !!axiosOptions.doNotSerializeParams);
|
|
1422
|
+
const isFormData = CLASS.getNameFromObject(requestBody) === 'FormData';
|
|
1423
|
+
const body = isFormData
|
|
1424
|
+
? requestBody
|
|
1425
|
+
: requestBody
|
|
1426
|
+
? JSON.stringify(requestBody)
|
|
1427
|
+
: void 0;
|
|
1428
|
+
// console.log('this.customContentType', this.customContentType)
|
|
1429
|
+
if (this.customContentType) {
|
|
1430
|
+
const customHeaderKeys = this.customContentType.keys();
|
|
1431
|
+
const currentHeaderKeys = this._headers.keys();
|
|
1432
|
+
currentHeaderKeys
|
|
1433
|
+
.filter(key => !customHeaderKeys.includes(key))
|
|
1434
|
+
.forEach(key => {
|
|
1435
|
+
this.customContentType.set(key, this._headers.get(key));
|
|
1436
|
+
});
|
|
1437
|
+
this._headers = this.customContentType;
|
|
1438
|
+
}
|
|
1439
|
+
else {
|
|
1440
|
+
this._headers = RestHeaders.from(CONTENT_TYPE.APPLICATION_JSON);
|
|
1441
|
+
}
|
|
1442
|
+
// console.log("_headers", this.headers)
|
|
1443
|
+
const result = this.request[method.toLowerCase()](modelUrl, body, this.headers, this.meta, isArray, this.mockHttp, axiosOptions);
|
|
1444
|
+
this.mockHttp = void 0;
|
|
1445
|
+
return result;
|
|
1446
|
+
}
|
|
1447
|
+
get(item, params, axiosOptions) {
|
|
1448
|
+
return this.req('get', item, params, axiosOptions);
|
|
1449
|
+
}
|
|
1450
|
+
head(item, params, axiosOptions) {
|
|
1451
|
+
return this.req('head', item, params, axiosOptions);
|
|
1452
|
+
}
|
|
1453
|
+
post(item, params, axiosOptions) {
|
|
1454
|
+
return this.req('post', item, params, axiosOptions);
|
|
1455
|
+
}
|
|
1456
|
+
put(item, params, axiosOptions) {
|
|
1457
|
+
return this.req('put', item, params, axiosOptions);
|
|
1458
|
+
}
|
|
1459
|
+
patch(item, params, axiosOptions) {
|
|
1460
|
+
return this.req('patch', item, params, axiosOptions);
|
|
1461
|
+
}
|
|
1462
|
+
delete(item, params, axiosOptions) {
|
|
1463
|
+
return this.req('delete', item, params, axiosOptions);
|
|
1464
|
+
}
|
|
1465
|
+
jsonp(item, params, axiosOptions) {
|
|
1466
|
+
return this.req('jsonp', item, params, axiosOptions);
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
//#endregion
|
|
1471
|
+
// const log = Log.create('resouce-service', Level.__NOTHING);
|
|
1472
|
+
class Resource {
|
|
1473
|
+
static { this._listenErrors = new Subject(); }
|
|
1474
|
+
static { this._listenSuccess = new Subject(); }
|
|
1475
|
+
static get listenErrors() {
|
|
1476
|
+
return this._listenErrors.asObservable();
|
|
1477
|
+
}
|
|
1478
|
+
static get listenSuccessOperations() {
|
|
1479
|
+
return this._listenSuccess.asObservable();
|
|
1480
|
+
}
|
|
1481
|
+
static { this.enableWarnings = true; }
|
|
1482
|
+
//#region private mthods and fields
|
|
1483
|
+
checkNestedModels(model, allModels) {
|
|
1484
|
+
// if (model.indexOf('/') !== -1) { //TODO make this better, becouse now I unecesary checking shit
|
|
1485
|
+
for (let p in allModels) {
|
|
1486
|
+
if (allModels.hasOwnProperty(p)) {
|
|
1487
|
+
let m = allModels[p];
|
|
1488
|
+
if (isValid(p)) {
|
|
1489
|
+
let urlModels = getModels(p);
|
|
1490
|
+
if (containsModels(model, urlModels)) {
|
|
1491
|
+
model = p;
|
|
1492
|
+
break;
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
// }
|
|
1498
|
+
return model;
|
|
1499
|
+
}
|
|
1500
|
+
static { this.instance = new Resource(); }
|
|
1501
|
+
static { this.endpoints = {}; }
|
|
1502
|
+
static getModel(endpoint, model) {
|
|
1503
|
+
model = Resource.prepareModel(model);
|
|
1504
|
+
const e = Resource.endpoints[endpoint];
|
|
1505
|
+
if (!e) {
|
|
1506
|
+
return void 0;
|
|
1507
|
+
}
|
|
1508
|
+
const r = Resource.endpoints[endpoint].models[model];
|
|
1509
|
+
return Resource.endpoints[endpoint].models[model];
|
|
1510
|
+
}
|
|
1511
|
+
static { this.request = new RestRequest(); }
|
|
1512
|
+
//#endregion
|
|
1513
|
+
//#region create
|
|
1514
|
+
static create(e, model, entityMapping, circular, customContentType) {
|
|
1515
|
+
const badRestRegEX = new RegExp('((\/:)[a-z]+)+', 'g');
|
|
1516
|
+
const matchArr = model.match(badRestRegEX) || [];
|
|
1517
|
+
const badModelsNextToEachOther = matchArr.join();
|
|
1518
|
+
const atleas2DoubleDots = (badModelsNextToEachOther.match(new RegExp(':', 'g')) || []).length >= 2;
|
|
1519
|
+
if (atleas2DoubleDots && model.search(badModelsNextToEachOther) !== -1) {
|
|
1520
|
+
throw new Error(`
|
|
1521
|
+
|
|
1522
|
+
Bad rest model: ${model}
|
|
1523
|
+
|
|
1524
|
+
Do not create rest models like this: /book/author/:bookid/:authorid
|
|
1525
|
+
Instead use nested approach: /book/:bookid/author/:authorid
|
|
1526
|
+
`);
|
|
1527
|
+
}
|
|
1528
|
+
Resource.map(e, e);
|
|
1529
|
+
Resource.instance.add(e, model ? model : '', entityMapping, circular, customContentType);
|
|
1530
|
+
// if (model.charAt(model.length - 1) !== '/') model = `${model}/`;
|
|
1531
|
+
return {
|
|
1532
|
+
model: (params) => Resource.instance.api(e, interpolateParamsToUrl(params, model)),
|
|
1533
|
+
get headers() {
|
|
1534
|
+
return Resource.getModel(e, model).headers;
|
|
1535
|
+
},
|
|
1536
|
+
};
|
|
1537
|
+
}
|
|
1538
|
+
//#endregion
|
|
1539
|
+
//#region reset
|
|
1540
|
+
static reset() {
|
|
1541
|
+
Resource.endpoints = {};
|
|
1542
|
+
}
|
|
1543
|
+
//#endregion
|
|
1544
|
+
//#region constructor
|
|
1545
|
+
constructor() { }
|
|
1546
|
+
//#endregion
|
|
1547
|
+
static { this.Cookies = Cookie.Instance; }
|
|
1548
|
+
//#region map
|
|
1549
|
+
static map(endpoint, url) {
|
|
1550
|
+
// log.i('url', url);
|
|
1551
|
+
let regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
|
|
1552
|
+
let e = endpoint;
|
|
1553
|
+
if (!regex.test(url)) {
|
|
1554
|
+
throw `Url address is not correct: ${url}`;
|
|
1555
|
+
}
|
|
1556
|
+
if (url.charAt(url.length - 1) === '/')
|
|
1557
|
+
url = url.slice(0, url.length - 1);
|
|
1558
|
+
// log.i('url after', url);
|
|
1559
|
+
if (Resource.endpoints[e] !== void 0) {
|
|
1560
|
+
// Helpers.log(
|
|
1561
|
+
// 'Cannot use map function at the same API endpoint again (' +
|
|
1562
|
+
// Resource.endpoints[e].url +
|
|
1563
|
+
// ')',
|
|
1564
|
+
// );
|
|
1565
|
+
return false;
|
|
1566
|
+
}
|
|
1567
|
+
Resource.endpoints[e] = {
|
|
1568
|
+
url: url,
|
|
1569
|
+
models: {},
|
|
1570
|
+
entity: null,
|
|
1571
|
+
};
|
|
1572
|
+
// log.i('enpoints', Resource.endpoints);
|
|
1573
|
+
return true;
|
|
1574
|
+
}
|
|
1575
|
+
//#endregion
|
|
1576
|
+
static prepareModel(model) {
|
|
1577
|
+
if (model.charAt(model.length - 1) === '/') {
|
|
1578
|
+
model = model.slice(0, model.length - 1);
|
|
1579
|
+
}
|
|
1580
|
+
if (model.charAt(0) === '/') {
|
|
1581
|
+
model = model.slice(1, model.length);
|
|
1582
|
+
}
|
|
1583
|
+
return model;
|
|
1584
|
+
}
|
|
1585
|
+
//#region add
|
|
1586
|
+
/**
|
|
1587
|
+
* And enipoint to application
|
|
1588
|
+
*
|
|
1589
|
+
* @param {E} endpoint
|
|
1590
|
+
* @param {string} model
|
|
1591
|
+
* @returns {boolean}
|
|
1592
|
+
*/
|
|
1593
|
+
add(endpoint, model, entity, circular, customContentType) {
|
|
1594
|
+
// log.i(`I am maping ${model} on ${<any>endpoint}`);
|
|
1595
|
+
model = Resource.prepareModel(model);
|
|
1596
|
+
let e;
|
|
1597
|
+
e = endpoint.toString();
|
|
1598
|
+
if (Resource.endpoints[e] === void 0) {
|
|
1599
|
+
console.error('Endpoint is not mapped ! Cannot add model ' + model);
|
|
1600
|
+
return;
|
|
1601
|
+
}
|
|
1602
|
+
if (Resource.endpoints[e].models[model] !== void 0) {
|
|
1603
|
+
if (Resource.enableWarnings)
|
|
1604
|
+
console.warn(`Model '${model}' is already defined in endpoint: ` +
|
|
1605
|
+
Resource.endpoints[e].url);
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
Resource.endpoints[e].models[model] = new Rest(Resource.endpoints[e].url + '/' + model, Resource.request, {
|
|
1609
|
+
endpoint: e,
|
|
1610
|
+
path: model,
|
|
1611
|
+
entity,
|
|
1612
|
+
circular,
|
|
1613
|
+
}, customContentType); // TODO put custom content type in meta ?
|
|
1614
|
+
return;
|
|
1615
|
+
}
|
|
1616
|
+
//#endregion
|
|
1617
|
+
//#region api
|
|
1618
|
+
/**
|
|
1619
|
+
* Access api throught endpoint
|
|
1620
|
+
*
|
|
1621
|
+
* @param {E} endpoint
|
|
1622
|
+
* @param {string} model
|
|
1623
|
+
* @returns {Rest<T, TA>}
|
|
1624
|
+
*/
|
|
1625
|
+
api(endpoint, model) {
|
|
1626
|
+
// log.i(`[api]
|
|
1627
|
+
// creating for endpoint: "${endpoint}"
|
|
1628
|
+
// model: "${model}"
|
|
1629
|
+
// `)
|
|
1630
|
+
if (model.charAt(0) === '/')
|
|
1631
|
+
model = model.slice(1, model.length);
|
|
1632
|
+
let e = endpoint.toString();
|
|
1633
|
+
if (Resource.endpoints[e] === void 0) {
|
|
1634
|
+
throw `Endpoint: ${endpoint} is not mapped ! Cannot add model: ${model}`;
|
|
1635
|
+
}
|
|
1636
|
+
let allModels = Resource.endpoints[e].models;
|
|
1637
|
+
let orgModel = model;
|
|
1638
|
+
model = this.checkNestedModels(model, allModels);
|
|
1639
|
+
if (Resource.endpoints[e].models[model] === void 0) {
|
|
1640
|
+
// log.d('Resource.endpoints', Resource.endpoints);
|
|
1641
|
+
throw `Model '${model}' is undefined in endpoint: ${Resource.endpoints[e].url} `;
|
|
1642
|
+
}
|
|
1643
|
+
let res = Resource.endpoints[endpoint.toString()].models[model];
|
|
1644
|
+
// log.d(`
|
|
1645
|
+
// orgModel: ${orgModel}
|
|
1646
|
+
// model: ${model}
|
|
1647
|
+
// `)
|
|
1648
|
+
if (orgModel !== model) {
|
|
1649
|
+
let baseUrl = Resource.endpoints[endpoint.toString()].url;
|
|
1650
|
+
// log.d('base', Resource.endpoints[<string>(endpoint).toString()])
|
|
1651
|
+
// log.d('baseUrl', baseUrl)
|
|
1652
|
+
// log.d('orgModel', orgModel)
|
|
1653
|
+
res.__rest_endpoint = `${baseUrl}/${orgModel}`;
|
|
1654
|
+
}
|
|
1655
|
+
else {
|
|
1656
|
+
res.__rest_endpoint = void 0;
|
|
1657
|
+
}
|
|
1658
|
+
// log.i(`Resource.endpoints`, Resource.endpoints)
|
|
1659
|
+
return res;
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
// const res = Resource.create('')
|
|
1663
|
+
// res.model()
|
|
1664
|
+
// .mock({
|
|
1665
|
+
// code: 500,
|
|
1666
|
+
// data: {},
|
|
1667
|
+
// isArray: true
|
|
1668
|
+
// })
|
|
1669
|
+
// .array.
|
|
1670
|
+
|
|
1671
|
+
/**
|
|
1672
|
+
*
|
|
1673
|
+
* @export
|
|
1674
|
+
* @abstract
|
|
1675
|
+
* @class SimpleResource
|
|
1676
|
+
* @extends {Resource<T, A, TA>}
|
|
1677
|
+
* @template E Endpoint type
|
|
1678
|
+
* @template A Single modle type
|
|
1679
|
+
* @template TA Array Model Type
|
|
1680
|
+
* @template RP rest url parameters type
|
|
1681
|
+
* @template QP query parameter type
|
|
1682
|
+
*/
|
|
1683
|
+
class ExtendedResource {
|
|
1684
|
+
static { this.doNotSerializeQueryParams = false; }
|
|
1685
|
+
static { this.handlers = []; }
|
|
1686
|
+
// add(endpoint: E, model: string, group?: string, name?: string, description?: string) { }
|
|
1687
|
+
constructor(endpoint, path_model) {
|
|
1688
|
+
this.endpoint = endpoint;
|
|
1689
|
+
this.path_model = path_model;
|
|
1690
|
+
/**
|
|
1691
|
+
* Get model by rest params
|
|
1692
|
+
*/
|
|
1693
|
+
this.model = (restParams) => {
|
|
1694
|
+
return {
|
|
1695
|
+
get: (item, queryPrams) => {
|
|
1696
|
+
return Observable.create((observer) => {
|
|
1697
|
+
ExtendedResource.handlers.push(this.rest
|
|
1698
|
+
.model(restParams)
|
|
1699
|
+
.get(item, [queryPrams], {
|
|
1700
|
+
doNotSerializeParams: ExtendedResource.doNotSerializeQueryParams,
|
|
1701
|
+
})
|
|
1702
|
+
.observable.subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
|
|
1703
|
+
});
|
|
1704
|
+
},
|
|
1705
|
+
patch: (item, queryParams) => {
|
|
1706
|
+
return Observable.create((observer) => {
|
|
1707
|
+
ExtendedResource.handlers.push(this.rest
|
|
1708
|
+
.model(restParams)
|
|
1709
|
+
.put(item, [queryParams], {
|
|
1710
|
+
doNotSerializeParams: ExtendedResource.doNotSerializeQueryParams,
|
|
1711
|
+
})
|
|
1712
|
+
.observable.subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
|
|
1713
|
+
});
|
|
1714
|
+
},
|
|
1715
|
+
head: (item, queryPrams) => {
|
|
1716
|
+
return Observable.create((observer) => {
|
|
1717
|
+
ExtendedResource.handlers.push(this.rest
|
|
1718
|
+
.model(restParams)
|
|
1719
|
+
.head(item, [queryPrams], {
|
|
1720
|
+
doNotSerializeParams: ExtendedResource.doNotSerializeQueryParams,
|
|
1721
|
+
})
|
|
1722
|
+
.observable.subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
|
|
1723
|
+
});
|
|
1724
|
+
},
|
|
1725
|
+
query: (item, queryPrams) => {
|
|
1726
|
+
return Observable.create((observer) => {
|
|
1727
|
+
ExtendedResource.handlers.push(this.rest
|
|
1728
|
+
.model(restParams)
|
|
1729
|
+
.array.get(item, [queryPrams], {
|
|
1730
|
+
doNotSerializeParams: ExtendedResource.doNotSerializeQueryParams,
|
|
1731
|
+
})
|
|
1732
|
+
.observable.subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
|
|
1733
|
+
});
|
|
1734
|
+
},
|
|
1735
|
+
post: (item, queryParams) => {
|
|
1736
|
+
return Observable.create((observer) => {
|
|
1737
|
+
ExtendedResource.handlers.push(this.rest
|
|
1738
|
+
.model(restParams)
|
|
1739
|
+
.post(item, [queryParams], {
|
|
1740
|
+
doNotSerializeParams: ExtendedResource.doNotSerializeQueryParams,
|
|
1741
|
+
})
|
|
1742
|
+
.observable.subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
|
|
1743
|
+
});
|
|
1744
|
+
},
|
|
1745
|
+
put: (item, queryParams) => {
|
|
1746
|
+
return Observable.create((observer) => {
|
|
1747
|
+
ExtendedResource.handlers.push(this.rest
|
|
1748
|
+
.model(restParams)
|
|
1749
|
+
.put(item, [queryParams], {
|
|
1750
|
+
doNotSerializeParams: ExtendedResource.doNotSerializeQueryParams,
|
|
1751
|
+
})
|
|
1752
|
+
.observable.subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
|
|
1753
|
+
});
|
|
1754
|
+
},
|
|
1755
|
+
delete: (item, queryPrams) => {
|
|
1756
|
+
return Observable.create((observer) => {
|
|
1757
|
+
ExtendedResource.handlers.push(this.rest
|
|
1758
|
+
.model(restParams)
|
|
1759
|
+
.delete(item, [queryPrams], {
|
|
1760
|
+
doNotSerializeParams: ExtendedResource.doNotSerializeQueryParams,
|
|
1761
|
+
})
|
|
1762
|
+
.observable.subscribe(data => observer.next(data.body.json), err => observer.error(err), () => observer.complete()));
|
|
1763
|
+
});
|
|
1764
|
+
},
|
|
1765
|
+
};
|
|
1766
|
+
};
|
|
1767
|
+
this.rest = Resource.create(endpoint, path_model);
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
*
|
|
1772
|
+
* @export
|
|
1773
|
+
* @class SimpleResource
|
|
1774
|
+
* @template A single model type
|
|
1775
|
+
* @template TA array model type
|
|
1776
|
+
* @template RP rest parameters type
|
|
1777
|
+
* @template QP query parameters type
|
|
1778
|
+
*/
|
|
1779
|
+
class SimpleResource {
|
|
1780
|
+
static { this._isSetQueryParamsSerialization = false; }
|
|
1781
|
+
static set doNotSerializeQueryParams(value) {
|
|
1782
|
+
if (!SimpleResource._isSetQueryParamsSerialization) {
|
|
1783
|
+
SimpleResource._isSetQueryParamsSerialization = true;
|
|
1784
|
+
ExtendedResource.doNotSerializeQueryParams = value;
|
|
1785
|
+
return;
|
|
1786
|
+
}
|
|
1787
|
+
console.warn(`Query params serialization already set as
|
|
1788
|
+
${ExtendedResource.doNotSerializeQueryParams},`);
|
|
1789
|
+
}
|
|
1790
|
+
static __destroy() {
|
|
1791
|
+
ExtendedResource.handlers.forEach(h => h.unsubscribe());
|
|
1792
|
+
}
|
|
1793
|
+
constructor(endpoint, model) {
|
|
1794
|
+
let rest = new ExtendedResource(endpoint, model);
|
|
1795
|
+
this.model = rest.model;
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1799
|
+
/**
|
|
1800
|
+
* Generated bundle index. Do not edit.
|
|
1801
|
+
*/
|
|
1802
|
+
|
|
1803
|
+
export { AxiosBackendHandler, CONTENT_TYPE, Helpers, HttpResponseError, Mapping, Models, Resource, Rest, RestErrorResponseWrapper, RestHeaders, RestResponseWrapper, SimpleResource, buildInterceptorChain, interpolateParamsToUrl };
|
|
1804
|
+
//# sourceMappingURL=ng2-rest-websql.mjs.map
|