@sdflc/backend-helpers 1.0.78 → 1.0.79
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/build/BaseCore.js +0 -3
- package/build/BaseGateway.js +0 -2
- package/build/RedisDataLoader.js +7 -12
- package/build/commonValidators.js +3 -9
- package/build/esm/BaseCore.d.ts +88 -0
- package/build/esm/BaseCore.js +810 -0
- package/build/esm/BaseGateway.d.ts +49 -0
- package/build/esm/BaseGateway.js +476 -0
- package/build/esm/DataCache.d.ts +14 -0
- package/build/esm/DataCache.js +98 -0
- package/build/esm/Database.d.ts +32 -0
- package/build/esm/Database.js +192 -0
- package/build/esm/DbMigratorAndSeeder.d.ts +49 -0
- package/build/esm/DbMigratorAndSeeder.js +199 -0
- package/build/esm/RedisDataLoader.d.ts +41 -0
- package/build/esm/RedisDataLoader.js +237 -0
- package/build/esm/apiContext.d.ts +11 -0
- package/build/esm/apiContext.js +135 -0
- package/build/esm/baseController.d.ts +17 -0
- package/build/esm/baseController.js +60 -0
- package/build/esm/checkItHelpers.d.ts +3 -0
- package/build/esm/checkItHelpers.js +23 -0
- package/build/esm/commonValidators.d.ts +17 -0
- package/build/esm/commonValidators.js +273 -0
- package/build/esm/configBulder.d.ts +2 -0
- package/build/esm/configBulder.js +28 -0
- package/build/esm/constants.d.ts +30 -0
- package/build/esm/constants.js +69 -0
- package/build/esm/dbHelpers.d.ts +43 -0
- package/build/esm/dbHelpers.js +154 -0
- package/build/esm/dbSeeder.d.ts +2 -0
- package/build/esm/dbSeeder.js +53 -0
- package/build/esm/dbTableHelpers.d.ts +11 -0
- package/build/esm/dbTableHelpers.js +99 -0
- package/build/esm/downloadHelpers.d.ts +2 -0
- package/build/esm/downloadHelpers.js +76 -0
- package/build/esm/index.d.ts +21 -0
- package/build/esm/index.js +21 -0
- package/build/esm/interfaces/ApiContext.d.ts +24 -0
- package/build/esm/interfaces/ApiContext.js +1 -0
- package/build/esm/interfaces/ApiContextInterface.d.ts +12 -0
- package/build/esm/interfaces/ApiContextInterface.js +1 -0
- package/build/esm/interfaces/BaseCoreActionsInterface.d.ts +38 -0
- package/build/esm/interfaces/BaseCoreActionsInterface.js +1 -0
- package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.d.ts +12 -0
- package/build/esm/interfaces/BaseCoreDoAuthOnActionInterface.js +1 -0
- package/build/esm/interfaces/BaseCoreDoingWhatInterface.d.ts +13 -0
- package/build/esm/interfaces/BaseCoreDoingWhatInterface.js +1 -0
- package/build/esm/interfaces/BaseCorePropsInterface.d.ts +36 -0
- package/build/esm/interfaces/BaseCorePropsInterface.js +1 -0
- package/build/esm/interfaces/BaseCoreValidatorsInterface.d.ts +13 -0
- package/build/esm/interfaces/BaseCoreValidatorsInterface.js +1 -0
- package/build/esm/interfaces/BaseGatewayPropsInterface.d.ts +39 -0
- package/build/esm/interfaces/BaseGatewayPropsInterface.js +1 -0
- package/build/esm/interfaces/BuildConfigOptions.d.ts +6 -0
- package/build/esm/interfaces/BuildConfigOptions.js +1 -0
- package/build/esm/interfaces/BuildDefaultResolversOptions.d.ts +17 -0
- package/build/esm/interfaces/BuildDefaultResolversOptions.js +1 -0
- package/build/esm/interfaces/BuildListQueryArgsInterface.d.ts +6 -0
- package/build/esm/interfaces/BuildListQueryArgsInterface.js +1 -0
- package/build/esm/interfaces/CacheInterface.d.ts +15 -0
- package/build/esm/interfaces/CacheInterface.js +1 -0
- package/build/esm/interfaces/CommonValidatorArgs.d.ts +3 -0
- package/build/esm/interfaces/CommonValidatorArgs.js +1 -0
- package/build/esm/interfaces/CoreActionInterface.d.ts +14 -0
- package/build/esm/interfaces/CoreActionInterface.js +1 -0
- package/build/esm/interfaces/CreateUserTokenArgs.d.ts +11 -0
- package/build/esm/interfaces/CreateUserTokenArgs.js +1 -0
- package/build/esm/interfaces/CreateUserTokenResult.d.ts +4 -0
- package/build/esm/interfaces/CreateUserTokenResult.js +1 -0
- package/build/esm/interfaces/DatabaseOptions.d.ts +22 -0
- package/build/esm/interfaces/DatabaseOptions.js +1 -0
- package/build/esm/interfaces/DatabaseReadInterface.d.ts +14 -0
- package/build/esm/interfaces/DatabaseReadInterface.js +1 -0
- package/build/esm/interfaces/DbFieldAddDefaultInterface.d.ts +9 -0
- package/build/esm/interfaces/DbFieldAddDefaultInterface.js +1 -0
- package/build/esm/interfaces/DownloadFileArgs.d.ts +6 -0
- package/build/esm/interfaces/DownloadFileArgs.js +1 -0
- package/build/esm/interfaces/ExtractCredentialsArgs.d.ts +19 -0
- package/build/esm/interfaces/ExtractCredentialsArgs.js +1 -0
- package/build/esm/interfaces/JwtTokenSecretAndSettings.d.ts +5 -0
- package/build/esm/interfaces/JwtTokenSecretAndSettings.js +1 -0
- package/build/esm/interfaces/ListArgsInterface.d.ts +5 -0
- package/build/esm/interfaces/ListArgsInterface.js +1 -0
- package/build/esm/interfaces/LoaderInterface.d.ts +4 -0
- package/build/esm/interfaces/LoaderInterface.js +1 -0
- package/build/esm/interfaces/PaginationInterface.d.ts +7 -0
- package/build/esm/interfaces/PaginationInterface.js +1 -0
- package/build/esm/interfaces/SortItemInterface.d.ts +4 -0
- package/build/esm/interfaces/SortItemInterface.js +1 -0
- package/build/esm/interfaces/UserTokenParams.d.ts +8 -0
- package/build/esm/interfaces/UserTokenParams.js +1 -0
- package/build/esm/interfaces/VerifyUserTokenArgs.d.ts +13 -0
- package/build/esm/interfaces/VerifyUserTokenArgs.js +1 -0
- package/build/esm/interfaces/index.d.ts +28 -0
- package/build/esm/interfaces/index.js +27 -0
- package/build/esm/knexConfigBuilder.d.ts +1 -0
- package/build/esm/knexConfigBuilder.js +73 -0
- package/build/esm/passwordHelpers.d.ts +5 -0
- package/build/esm/passwordHelpers.js +22 -0
- package/build/esm/redisClient.d.ts +17 -0
- package/build/esm/redisClient.js +94 -0
- package/build/esm/resolversHelpers.d.ts +3 -0
- package/build/esm/resolversHelpers.js +59 -0
- package/build/esm/userToken.d.ts +8 -0
- package/build/esm/userToken.js +74 -0
- package/build/esm/utils.d.ts +2 -0
- package/build/esm/utils.js +13 -0
- package/package.json +13 -5
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { isObject, last, map, omit, pick } from 'lodash';
|
|
11
|
+
import DataLoader from 'dataloader';
|
|
12
|
+
import stringify from 'json-stable-stringify';
|
|
13
|
+
const customOptions = ['expire', 'serialize', 'deserialize', 'cacheKeyFn'];
|
|
14
|
+
const mapPromise = (promise, fn) => Promise.all(promise.map(fn));
|
|
15
|
+
class RedisDataLoader {
|
|
16
|
+
constructor(redisClient, keySpace, userLoader, opt) {
|
|
17
|
+
this.redisClient = redisClient;
|
|
18
|
+
this.opt = pick(opt, customOptions) || {};
|
|
19
|
+
this.dataLoaderOpt = Object.assign(Object.assign({}, omit(opt, customOptions)), { cacheKeyFn: this.opt.cacheKeyFn });
|
|
20
|
+
this.opt.cacheKeyFn =
|
|
21
|
+
typeof this.opt.cacheKeyFn === 'function'
|
|
22
|
+
? this.opt.cacheKeyFn
|
|
23
|
+
: (key) => (isObject(key) ? stringify(key) : key);
|
|
24
|
+
this.keySpace = keySpace ? keySpace + ':' : '';
|
|
25
|
+
this.loader = new DataLoader((keys) => __awaiter(this, void 0, void 0, function* () {
|
|
26
|
+
const results = yield this.rMGet(keys);
|
|
27
|
+
const keysToRead = [];
|
|
28
|
+
const keysIdxsToRead = [];
|
|
29
|
+
keys.forEach((key, idx) => {
|
|
30
|
+
if (results[idx] == null) {
|
|
31
|
+
keysToRead.push(key);
|
|
32
|
+
keysIdxsToRead.push(idx);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
if (keysToRead.length > 0) {
|
|
36
|
+
const loadedData = yield userLoader.load(keysToRead);
|
|
37
|
+
const data = yield this.rMSetAndGet(keysToRead, loadedData);
|
|
38
|
+
keysIdxsToRead.forEach((keyIdx, idx) => {
|
|
39
|
+
results[keyIdx] = data[idx];
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
return results;
|
|
43
|
+
}), this.dataLoaderOpt);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Adds a prefix to the passed key
|
|
47
|
+
* @param key Key value
|
|
48
|
+
* @returns Trasnformed key value that includes key space
|
|
49
|
+
*/
|
|
50
|
+
makeKey(key) {
|
|
51
|
+
return `${this.keySpace}${this.opt.cacheKeyFn(key)}`;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Deserializes response from Readis
|
|
55
|
+
* @param str String to deserialize
|
|
56
|
+
* @returns
|
|
57
|
+
*/
|
|
58
|
+
parse(str) {
|
|
59
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
60
|
+
if (str === '' || str === null) {
|
|
61
|
+
return str;
|
|
62
|
+
}
|
|
63
|
+
else if (typeof this.opt.deserialize === 'function') {
|
|
64
|
+
return yield this.opt.deserialize(str);
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
return JSON.parse(str);
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Serializes passed value to a string
|
|
73
|
+
* @param value A value to be serialized
|
|
74
|
+
* @returns serialized value in the form of string
|
|
75
|
+
*/
|
|
76
|
+
toString(value) {
|
|
77
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
78
|
+
if (value === null) {
|
|
79
|
+
return '';
|
|
80
|
+
}
|
|
81
|
+
else if (typeof this.opt.serialize === 'function') {
|
|
82
|
+
return yield this.opt.serialize(value);
|
|
83
|
+
}
|
|
84
|
+
else if (isObject(value)) {
|
|
85
|
+
return JSON.stringify(value);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
throw new Error(RedisDataLoader.messages.valueObjectOrNull);
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
rSetAndGet(key, rawValue) {
|
|
93
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
94
|
+
const value = yield this.toString(rawValue);
|
|
95
|
+
const fullKey = this.makeKey(key);
|
|
96
|
+
const multi = this.redisClient.multi();
|
|
97
|
+
multi.set(fullKey, value);
|
|
98
|
+
if (this.opt.expire) {
|
|
99
|
+
multi.expire(fullKey, this.opt.expire);
|
|
100
|
+
}
|
|
101
|
+
multi.get(fullKey);
|
|
102
|
+
const replies = yield multi.exec();
|
|
103
|
+
const lastReply = last(replies);
|
|
104
|
+
const result = yield this.parse(lastReply);
|
|
105
|
+
return result;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
rMSetAndGet(keys, rawValues) {
|
|
109
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
110
|
+
const multi = this.redisClient.multi();
|
|
111
|
+
const fullKeys = yield mapPromise(keys, (key) => this.makeKey(key));
|
|
112
|
+
const values = yield mapPromise(rawValues, (rawValue) => this.toString(rawValue));
|
|
113
|
+
multi.mSet(fullKeys.reduce((acc, fullKey, idx) => {
|
|
114
|
+
acc.push(fullKey);
|
|
115
|
+
acc.push(values[idx]);
|
|
116
|
+
return acc;
|
|
117
|
+
}, []));
|
|
118
|
+
if (this.opt.expire) {
|
|
119
|
+
for (const fullKey of fullKeys) {
|
|
120
|
+
multi.expire(fullKey, this.opt.expire);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
multi.mGet(fullKeys);
|
|
124
|
+
const replies = yield multi.exec();
|
|
125
|
+
const lastReplies = last(replies);
|
|
126
|
+
const result = yield mapPromise(lastReplies, (lastReply) => this.parse(lastReply));
|
|
127
|
+
return result;
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
rGet(key) {
|
|
131
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
132
|
+
const reply = yield this.redisClient.get(this.makeKey(key));
|
|
133
|
+
const result = yield this.parse(reply);
|
|
134
|
+
return result;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
rMGet(keys) {
|
|
138
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
139
|
+
const replies = yield this.redisClient.mGet(map(keys, (key) => this.makeKey(key)));
|
|
140
|
+
const results = yield mapPromise(replies, (reply) => this.parse(reply));
|
|
141
|
+
return results;
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
rSet(key, rawValue) {
|
|
145
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
146
|
+
const value = yield this.toString(rawValue);
|
|
147
|
+
const reply = yield this.redisClient.set(this.makeKey(key), value);
|
|
148
|
+
const result = yield this.parse(reply);
|
|
149
|
+
// result is expected to be OK
|
|
150
|
+
return result;
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
rMSet(keys, values) {
|
|
154
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
155
|
+
if (keys.length != values.length) {
|
|
156
|
+
throw new Error(RedisDataLoader.messages.keysValuesLengths);
|
|
157
|
+
}
|
|
158
|
+
const multi = this.redisClient.multi();
|
|
159
|
+
multi.mSet(keys.reduce((acc, key, idx) => {
|
|
160
|
+
acc.push(this.makeKey(key));
|
|
161
|
+
acc.push(values[idx]);
|
|
162
|
+
return acc;
|
|
163
|
+
}, []));
|
|
164
|
+
if (this.opt.expire) {
|
|
165
|
+
for (const key of keys) {
|
|
166
|
+
multi.expire(key, this.opt.expire);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
// The reply is expected to be "OK"
|
|
170
|
+
const reply = yield multi.exec();
|
|
171
|
+
return reply;
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
rDel(key) {
|
|
175
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
176
|
+
return yield this.redisClient.del(this.makeKey(key));
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
load(key) {
|
|
180
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
181
|
+
if (!key) {
|
|
182
|
+
throw new TypeError(RedisDataLoader.messages.keyRequired);
|
|
183
|
+
}
|
|
184
|
+
return yield this.loader.load(key);
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
loadMany(keys) {
|
|
188
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
189
|
+
if (!Array.isArray(keys)) {
|
|
190
|
+
throw new TypeError(RedisDataLoader.messages.keysArrayRequired);
|
|
191
|
+
}
|
|
192
|
+
return yield this.loader.loadMany(keys);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
prime(key, value) {
|
|
196
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
197
|
+
if (!key) {
|
|
198
|
+
throw new TypeError(RedisDataLoader.messages.keyRequired);
|
|
199
|
+
}
|
|
200
|
+
else if (value === undefined) {
|
|
201
|
+
throw new TypeError(RedisDataLoader.messages.valueRequired);
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
const result = yield this.rSetAndGet(key, value);
|
|
205
|
+
return yield this.loader.clear(key).prime(key, result === '' ? null : result);
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
clear(key) {
|
|
210
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
211
|
+
if (!key) {
|
|
212
|
+
throw new TypeError(RedisDataLoader.messages.keyRequired);
|
|
213
|
+
}
|
|
214
|
+
const resp = yield this.rDel(key);
|
|
215
|
+
yield this.loader.clear(key);
|
|
216
|
+
return resp;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
clearAllLocal() {
|
|
220
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
221
|
+
return yield this.loader.clearAll();
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
clearLocal(key) {
|
|
225
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
226
|
+
return yield this.loader.clear(key);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
RedisDataLoader.messages = {
|
|
231
|
+
keyRequired: 'The "key" parameter is required',
|
|
232
|
+
keysArrayRequired: 'The "keys" parameter is required and should be an array',
|
|
233
|
+
valueRequired: 'The "value" parameter is required',
|
|
234
|
+
valueObjectOrNull: 'The "value" parameter must be an object or null',
|
|
235
|
+
keysValuesLengths: 'The "keys" and "values" are expected to be the same',
|
|
236
|
+
};
|
|
237
|
+
export { RedisDataLoader };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ApiContext, ApiContextInterface } from './interfaces';
|
|
2
|
+
/**
|
|
3
|
+
* Creates a GraphQL context object with all available cores.
|
|
4
|
+
* @returns {object} A context object with all available cores
|
|
5
|
+
*/
|
|
6
|
+
export declare const createApiContext: (args: ApiContextInterface) => Promise<ApiContext>;
|
|
7
|
+
/**
|
|
8
|
+
* Creates default a GraphQL context object with all avilable cores.
|
|
9
|
+
* @returns {object} A context object with all available cores
|
|
10
|
+
*/
|
|
11
|
+
export declare const createContextDefault: (args: any) => Promise<ApiContext>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import { camelCase } from 'lodash';
|
|
11
|
+
import { v4 } from 'uuid';
|
|
12
|
+
import check from 'check-types';
|
|
13
|
+
import { extractLanguages } from '@sdflc/utils';
|
|
14
|
+
import { Database } from './Database';
|
|
15
|
+
import { HEADERS } from './constants';
|
|
16
|
+
/**
|
|
17
|
+
* Creates a GraphQL context object with all available cores.
|
|
18
|
+
* @returns {object} A context object with all available cores
|
|
19
|
+
*/
|
|
20
|
+
export const createApiContext = (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
21
|
+
const { cores, gateways, req, res, getCoreContext, getGatewayContext, extendContext, requestId: inRequestId, } = args || {};
|
|
22
|
+
const requestId = inRequestId || v4();
|
|
23
|
+
const coreContext = check.function(getCoreContext) ? yield getCoreContext({ req }) : {};
|
|
24
|
+
const gatewayContext = check.function(getGatewayContext) ? yield getGatewayContext({ req }) : {};
|
|
25
|
+
const context = {
|
|
26
|
+
requestId,
|
|
27
|
+
cores: {},
|
|
28
|
+
gateways: {},
|
|
29
|
+
usedKeyPrefixes: {},
|
|
30
|
+
req,
|
|
31
|
+
res,
|
|
32
|
+
};
|
|
33
|
+
context.cores = Object.keys(cores || {}).reduce((acc, key) => {
|
|
34
|
+
acc[camelCase(key)] = new cores[key](Object.assign(Object.assign({}, coreContext), { context }));
|
|
35
|
+
return acc;
|
|
36
|
+
}, {});
|
|
37
|
+
context.gateways = Object.keys(gateways || {}).reduce((acc, key) => {
|
|
38
|
+
acc[camelCase(key)] = new gateways[key](Object.assign(Object.assign({}, gatewayContext), { context }));
|
|
39
|
+
return acc;
|
|
40
|
+
}, {});
|
|
41
|
+
if (check.function(extendContext)) {
|
|
42
|
+
yield extendContext({ context, req });
|
|
43
|
+
}
|
|
44
|
+
return context;
|
|
45
|
+
});
|
|
46
|
+
/**
|
|
47
|
+
* Creates default a GraphQL context object with all avilable cores.
|
|
48
|
+
* @returns {object} A context object with all available cores
|
|
49
|
+
*/
|
|
50
|
+
export const createContextDefault = (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
51
|
+
const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
|
|
52
|
+
const headers = req.headers || { noHeadersSetup: true };
|
|
53
|
+
const cookies = req.cookies || { noCookiesSetup: true };
|
|
54
|
+
const authorization = (headers[HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
|
|
55
|
+
const fingerprint = headers[HEADERS.FINGERPRINT] || '';
|
|
56
|
+
const spaceId = headers[HEADERS.SPACE_ID];
|
|
57
|
+
const apiKey = headers[HEADERS.API_KEY];
|
|
58
|
+
const managementApiKey = headers[HEADERS.MANAGEMENT_API_KEY];
|
|
59
|
+
const userAgent = headers[HEADERS.USER_AGENT];
|
|
60
|
+
const referer = headers[HEADERS.REFERER];
|
|
61
|
+
const ipAddress = headers[HEADERS.IP_ADDRESS] || req.connection.remoteAddress;
|
|
62
|
+
const acceptLanguage = headers[HEADERS.ACCEPT_LANGUAGE];
|
|
63
|
+
const languages = extractLanguages(acceptLanguage);
|
|
64
|
+
const requestedLang = headers[HEADERS.REQUESTED_LANGUAGE] || (languages === null || languages === void 0 ? void 0 : languages[0]) || 'en';
|
|
65
|
+
// const accountId = headers[HEADERS.ACCOUNT_ID];
|
|
66
|
+
// const roleId = headers[HEADERS.ROLE_ID];
|
|
67
|
+
// const userId = headers[HEADERS.USER_ID];
|
|
68
|
+
const requestId = v4();
|
|
69
|
+
const db = inDb
|
|
70
|
+
? inDb
|
|
71
|
+
: new Database({
|
|
72
|
+
knexConfig,
|
|
73
|
+
dbSchema,
|
|
74
|
+
logger,
|
|
75
|
+
});
|
|
76
|
+
const sharedContext = {
|
|
77
|
+
spaceId,
|
|
78
|
+
apiKey,
|
|
79
|
+
managementApiKey,
|
|
80
|
+
userAgent,
|
|
81
|
+
referer,
|
|
82
|
+
ipAddress,
|
|
83
|
+
acceptLanguage,
|
|
84
|
+
languages,
|
|
85
|
+
requestedLang,
|
|
86
|
+
authorization,
|
|
87
|
+
fingerprint,
|
|
88
|
+
// accountId,
|
|
89
|
+
// roleId,
|
|
90
|
+
// userId,
|
|
91
|
+
req,
|
|
92
|
+
res,
|
|
93
|
+
headers,
|
|
94
|
+
cookies,
|
|
95
|
+
authorizationToken,
|
|
96
|
+
isExternalDb: !!inDb,
|
|
97
|
+
};
|
|
98
|
+
return yield createApiContext({
|
|
99
|
+
cores,
|
|
100
|
+
gateways,
|
|
101
|
+
req,
|
|
102
|
+
res,
|
|
103
|
+
requestId,
|
|
104
|
+
extendContext: (_a) => __awaiter(void 0, [_a], void 0, function* ({ context, req }) {
|
|
105
|
+
context.db = db;
|
|
106
|
+
Object.assign(context, sharedContext);
|
|
107
|
+
if (check.function(extendContext)) {
|
|
108
|
+
yield extendContext({ context, req });
|
|
109
|
+
}
|
|
110
|
+
}),
|
|
111
|
+
getCoreContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
112
|
+
// TODO: const { req } = args;
|
|
113
|
+
let extendCoreConext = {};
|
|
114
|
+
if (check.function(getCoreContext)) {
|
|
115
|
+
extendCoreConext = yield getCoreContext(args);
|
|
116
|
+
}
|
|
117
|
+
return Object.assign({ db, gatewayName: '', isProduction,
|
|
118
|
+
logger,
|
|
119
|
+
doAuth,
|
|
120
|
+
spaceGw,
|
|
121
|
+
interserviceApiKey,
|
|
122
|
+
jwtSecret,
|
|
123
|
+
verifyTokenArgs }, (extendCoreConext || {}));
|
|
124
|
+
}),
|
|
125
|
+
getGatewayContext: (args) => __awaiter(void 0, void 0, void 0, function* () {
|
|
126
|
+
let extendGatewayConext = {};
|
|
127
|
+
if (check.function(getGatewayContext)) {
|
|
128
|
+
extendGatewayConext = yield getGatewayContext(args);
|
|
129
|
+
}
|
|
130
|
+
return Object.assign({ db,
|
|
131
|
+
isProduction,
|
|
132
|
+
logger }, (extendGatewayConext || {}));
|
|
133
|
+
}),
|
|
134
|
+
});
|
|
135
|
+
});
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Logger } from '@sdflc/utils';
|
|
2
|
+
/**
|
|
3
|
+
* Base class for REST API controllers.
|
|
4
|
+
*/
|
|
5
|
+
declare class BaseController {
|
|
6
|
+
protected onResponse: any;
|
|
7
|
+
protected logger: Logger;
|
|
8
|
+
constructor(props: any);
|
|
9
|
+
init(props: any): void;
|
|
10
|
+
/**
|
|
11
|
+
* Executes an action method and returns result in consistent way.
|
|
12
|
+
* @param method a function to be executed
|
|
13
|
+
* @returns HTTP response
|
|
14
|
+
*/
|
|
15
|
+
json(method: any): (req: any, res: any, next: any) => Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export { BaseController };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
import check from 'check-types';
|
|
11
|
+
import { OpResult } from '@sdflc/api-helpers';
|
|
12
|
+
import { Logger, LoggerLevels } from '@sdflc/utils';
|
|
13
|
+
/**
|
|
14
|
+
* Base class for REST API controllers.
|
|
15
|
+
*/
|
|
16
|
+
class BaseController {
|
|
17
|
+
constructor(props) {
|
|
18
|
+
if (check.function(props === null || props === void 0 ? void 0 : props.onResponse)) {
|
|
19
|
+
this.onResponse = props === null || props === void 0 ? void 0 : props.onResponse;
|
|
20
|
+
}
|
|
21
|
+
else {
|
|
22
|
+
this.onResponse = () => {
|
|
23
|
+
/* TODO */
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
this.logger = (props === null || props === void 0 ? void 0 : props.logger) instanceof Logger ? props.logger : new Logger({ level: LoggerLevels.ERROR });
|
|
27
|
+
}
|
|
28
|
+
init(props) {
|
|
29
|
+
// const { app } = props;
|
|
30
|
+
// set express app routes here:
|
|
31
|
+
// app.post(`${root}/event-webhook`, this.json(this.eventWebhook));
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Executes an action method and returns result in consistent way.
|
|
35
|
+
* @param method a function to be executed
|
|
36
|
+
* @returns HTTP response
|
|
37
|
+
*/
|
|
38
|
+
json(method) {
|
|
39
|
+
return (req, res, next) => __awaiter(this, void 0, void 0, function* () {
|
|
40
|
+
try {
|
|
41
|
+
const result = yield method(req, res, next);
|
|
42
|
+
if (result instanceof OpResult) {
|
|
43
|
+
res.status(result.getHttpStatus()).json(result.toJS());
|
|
44
|
+
}
|
|
45
|
+
else if (result) {
|
|
46
|
+
res.status(200).json(result);
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
res.status(204).json(new OpResult());
|
|
50
|
+
}
|
|
51
|
+
yield this.onResponse(req, res, next);
|
|
52
|
+
}
|
|
53
|
+
catch (ex) {
|
|
54
|
+
this.logger.log(`An exception has occured when processing REST API request on the entry point '${req.method} ${req.originalUrl}' from ${req.ip}`);
|
|
55
|
+
next(ex);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export { BaseController };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { OpResult, OP_RESULT_CODES } from '@sdflc/api-helpers';
|
|
2
|
+
export const checkArray = (arr, validator, prefix) => {
|
|
3
|
+
const result = new OpResult();
|
|
4
|
+
if (!Array.isArray(arr)) {
|
|
5
|
+
return result.addError(prefix || '', 'The value should be an array');
|
|
6
|
+
}
|
|
7
|
+
arr.forEach((item, idx) => {
|
|
8
|
+
const [itemResult] = validator.validateSync(item);
|
|
9
|
+
if (itemResult) {
|
|
10
|
+
Object.keys(itemResult.errors).forEach((key) => {
|
|
11
|
+
result.addError(`${prefix || ''}[${idx}].${key}`, itemResult.errors[key].message);
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
return result;
|
|
16
|
+
};
|
|
17
|
+
export const createErrorOnCheckError = (checkItResult) => {
|
|
18
|
+
const result = new OpResult({ code: OP_RESULT_CODES.VALIDATION_FAILED });
|
|
19
|
+
Object.keys(checkItResult.errors).forEach((key) => {
|
|
20
|
+
result.addError(key, checkItResult.errors[key].message);
|
|
21
|
+
});
|
|
22
|
+
return result;
|
|
23
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { OpResult } from '@sdflc/api-helpers';
|
|
2
|
+
import { BaseCoreActionsInterface, CommonValidatorArgs } from './interfaces';
|
|
3
|
+
export declare const shouldHaveParams: (args: any) => boolean[] | OpResult[];
|
|
4
|
+
export declare const shouldHaveId: (id: any) => boolean[] | OpResult[];
|
|
5
|
+
export declare const validateSingleIntId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
6
|
+
export declare const validateSingleUuidId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
7
|
+
export declare const validateSingleTextId: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
8
|
+
export declare const validateMultipleIntIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
9
|
+
export declare const validateMultipleUuidIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
10
|
+
export declare const validateMultipleTextIds: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
11
|
+
export declare const validateList: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
12
|
+
export declare const validateGet: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
13
|
+
export declare const validateRemove: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
14
|
+
export declare const validateGetMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
15
|
+
export declare const validateRemoveMany: (args: any, opt: BaseCoreActionsInterface) => Promise<OpResult[] | {}[]>;
|
|
16
|
+
export declare const validateCreate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
|
|
17
|
+
export declare const validateUpdate: ({ rules }: CommonValidatorArgs) => (args: any, opt: BaseCoreActionsInterface) => Promise<{}[] | {}[]>;
|