-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRequestEngine.ts
More file actions
executable file
·563 lines (477 loc) · 14.5 KB
/
Copy pathRequestEngine.ts
File metadata and controls
executable file
·563 lines (477 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
import fs = require("fs");
import Path = require("path");
import ObjectCollection = require("object-collection");
import requestHelpers = require("./Functions/request.fn");
import ErrorEngine = require("./ErrorEngine");
import lodash = require("lodash");
import {Http} from "../types/http";
import {getInstance} from "../index";
import {DollarSign} from "../types";
import InXpresserError = require("./Errors/InXpresserError");
import express = require("express");
const ejs = require("ejs");
const $ = getInstance();
const PluginNameSpaces: any = $.engineData.get("PluginEngine:namespaces", {});
const useFlash = $.config.get("server.use.flash", false);
/**
* Get Request Engine Config
*/
const requestEngineConfig: {
dataKey: string,
proceedKey: string,
messageKey: string
} = $.config.get('server.requestEngine', {
dataKey: 'data',
proceedKey: 'proceed',
messageKey: 'message'
});
class RequestEngine {
public req: Http.Request;
public res: Http.Response;
public $query: ObjectCollection;
public $body: ObjectCollection;
public params: Record<string, any>;
public state: ObjectCollection;
public route: {
name: string,
method: string,
controller: string,
} = {
name: "",
method: "",
controller: "",
};
/**
*
* @param {*} req
* @param {*} res
* @param {*} next
* @param route
*/
constructor(req: Http.Request, res: Http.Response, next?: () => void, route?: any) {
this.res = res;
this.req = req;
if (typeof next === "function") this.next = next;
if (route) this.route = {
name: route.name || "",
method: route.method || "",
controller: typeof route.controller === "string"
? route.controller : "",
};
this.params = req.params || {};
// Set Default locals
if (!res.locals) res.locals = {};
// Set State
this.state = new ObjectCollection(res.locals);
// Set $body and $query
this.$body = new ObjectCollection(req.body || {});
this.$query = new ObjectCollection(req.query || {});
}
/**
* Takes in an xpresser middleware and returns an express middleware.
*
* Useful when dealing with express middlewares but want to use xpresser's RequestEngine.
*/
public static expressify(fn: (http: RequestEngine) => any) {
return (req: express.Request, res: express.Response, next: express.NextFunction) => {
return fn(new this(req, res, next));
}
}
/**
* If User has customRenderer then use it.
*/
customRenderer!: (...args: any[]) => string
/**
* Returns Current Xpresser Instance.
*/
$instance(): DollarSign {
return $;
}
/**
* Xpresser Instance Getter
* @param key
*/
$<K extends keyof DollarSign>(key: K): DollarSign[K] {
return $[key];
}
/**
* Returns an instance of ErrorEngine
*/
newError(e?: any): ErrorEngine {
return new ErrorEngine(this, e)
}
/**
* Request Next Function
*/
public next(): void {
// Next block is empty
}
/**
* Send Body
* @param body
* @param status
*/
public send(body: any, status?: number): Http.Response {
if (status) this.status(status);
return this.res.send(body);
}
/**
* Send Json Response
* @param body
* @param status
*/
public json(body: any, status?: number): Http.Response {
if (status) this.status(status);
return this.res.json(body);
}
/**
* Set response status
* @param code
*/
public status(code: number): this {
this.res.status(code);
return this;
}
/**
* Request Query Data
* @param [key]
* @param [$default]
* @returns {*|ObjectCollection}
*/
public query<T = unknown>(key?: string | undefined, $default?: T): T {
if (key === undefined) {
$.logDeprecated('0.3.22', '1.0.0', 'http.query() without arguments to get query collection is deprecated, use `http.$query` instead.');
// will be remove in version 1.0.0
return this.$query as any as T;
} else {
return this.$query.get(key, $default) as T;
}
}
/**
* Request Body Data
* @param [key]
* @param [$default]
* @example
* const body = http.body('inputName', 'defaultValue');
* const body = http.body(); // collection
* @returns {*|ObjectCollection}
*/
public body<T = unknown>(key?: string | undefined, $default?: T): T {
if (key === undefined) {
$.logDeprecated('0.3.22', '1.0.0', 'http.body() without keys to get body collection is deprecated, use `http.$body` instead.');
// will be remove in version 1.0.0
return this.$body as any as T;
} else {
return this.$body.get(key, $default) as T;
}
}
/**
* Check if param exists in current request.
* @param param
*/
public hasParam(param: string): boolean {
return this.params.hasOwnProperty(param);
}
/**
* Check if params exists in current request.
* @param params
*/
public hasParams(params: string[]): boolean {
if (!Array.isArray(params)) {
throw new InXpresserError(`hasParams: Expects argument params to be an array of params.`)
}
for (const param of params) {
if (!this.hasParam(param)) {
return false;
}
}
return true;
}
/**
* Get all or pluck keys
* @param pluck
* @returns {*}
*/
public all(pluck: any[] = []) {
const all = lodash.extend({}, this.req.query, this.req.body);
if (pluck.length) {
return lodash.pick(all, pluck);
}
return all;
}
/**
* To API format
* @param {*} data
* @param {boolean} proceed
* @param {number} status
*/
public toApi(data: any = {}, proceed = true, status?: number): Http.Response {
const d = {[requestEngineConfig.proceedKey]: proceed} as any;
if (data.hasOwnProperty(requestEngineConfig.messageKey)) {
d[requestEngineConfig.messageKey] = data[requestEngineConfig.messageKey];
delete data[requestEngineConfig.messageKey];
}
d.data = data;
if (status !== undefined) this.res.status(status);
return this.json(d, status);
}
/**
* Return false to Api
* @param {object} data
* @param {number} status
*/
public toApiFalse(data: object = {}, status: number = 200): Http.Response {
return this.toApi(data, false, status);
}
/**
* Say something true to your front end!
* @param {string} message
* @param {boolean} proceed
* @param {number} status
*/
public sayToApi(message: string, proceed = true, status = 200): Http.Response {
return this.toApi({
[requestEngineConfig.messageKey]: message,
}, proceed, status);
}
/**
* Say some error to your front end!
* @param {string} message
* @param {boolean} proceed
* @param {number} status
*/
public sayToApiFalse(message: string, proceed = false, status = 200): Http.Response {
return this.toApi({
[requestEngineConfig.messageKey]: message,
}, proceed, status);
}
/**
* Redirect to url.
* @param {string} path
* @returns {*}
*/
public redirect(path = "/"): any {
this.res.redirect(path);
return this.res.end();
}
/**
* Redirect Back
*/
public redirectBack(): any {
const backURL = this.req.header("Referer") || "/";
return this.redirect(backURL);
}
/**
* Redirect to route
* @param {string} route
* @param {Array|string} keys
* @param query
* @param includeUrl
* @returns {*}
*/
public redirectToRoute(route: string, keys?: any[], query?: object | boolean, includeUrl?: boolean): any {
return this.redirect($.helpers.route(route, keys, query, includeUrl));
}
/**
* View Data
* @param file
* @private
*/
protected viewData(file: string): any {
const localsConfig = $.config.get('template.locals');
const all = localsConfig.all;
let ctx: any;
ctx = lodash.extend({}, $.helpers, requestHelpers(this));
ctx.$route = this.route;
ctx.$currentView = file;
if (useFlash && this.req.flash) {
ctx.$flash = this.req.flash();
}
ctx.$currentUrl = this.req.url;
if (all) {
ctx.$query = this.req.query;
ctx.$body = this.req.body;
ctx.$stackedScripts = [];
} else {
if (localsConfig.stackedScripts) ctx.$stackedScripts = [];
if (localsConfig.query) ctx.$query = this.req.query;
if (localsConfig.body) ctx.$body = this.req.body;
}
this.res.locals["ctx"] = ctx;
return ctx;
}
/**
* Render View
* @param {string} file
* @param {Object} data
* @param {boolean} fullPath
* @param useInternalEjs
* @returns {*}
*/
public view(file: string, data = {}, fullPath: boolean = false, useInternalEjs: boolean = false): any {
/**
* Express Default Renderer
* @param args
*/
const defaultRender = (...args: any[]) => {
// @ts-ignore
return this.res.render(...args);
};
/**
* If RequestEngine has function this.customRenderer
* We use that function else we use express default.
*/
const Render = typeof this.customRenderer === "function" ? this.customRenderer : defaultRender;
const $filePath = file;
/**
* If view has namespace,
* We file the exact path to the file.
*/
if (file.indexOf("::") > 2) {
if ($.engineData.has("RequestEngine:views." + $filePath)) {
file = $.engineData.get("RequestEngine:views." + $filePath);
} else {
const $splitFile = file.split("::");
const $pluginNamespace = $splitFile[0];
if (PluginNameSpaces.hasOwnProperty($pluginNamespace)) {
const pluginNamespaceData = new ObjectCollection(PluginNameSpaces[$pluginNamespace])
const pluginViewsPath: any = pluginNamespaceData.get('paths.views', undefined);
if (pluginViewsPath && typeof pluginViewsPath === "string") {
file = pluginViewsPath + "/" + $splitFile[1];
$.engineData.path("RequestEngine:views").set($filePath, file);
}
}
}
}
/**
* Set file extension.
*/
const path = file + "." + (useInternalEjs ? "ejs" : $.config.get('template.extension'));
// Get xpresser view data
this.viewData($filePath);
if (typeof fullPath === "function") {
return Render(path, data, fullPath);
}
/**
* UseEjs if useInternalEjs is == true.
*/
if (useInternalEjs === true) {
data = Object.assign(this.res.locals, data);
return this.res.send(ejs.render(
fs.readFileSync(Path.resolve(path)).toString(),
data,
{filename: path},
));
} else {
try {
// @ts-ignore
return Render(...arguments);
} catch (e) {
$.logError(e);
}
}
}
/**
* @type RequestEngine.prototype.view
* @param args
* @return {*}
* @alias
*/
public renderView(...args: any[]): any {
// @ts-ignore
return this.view(...args);
}
/**
* @type RequestEngine.prototype.view
* @param args
* @return {*}
* @alias
*/
private render(...args: any[]): any {
// @ts-ignore
return this.view(...args);
}
/**
* Render View From Engine
* @param {string} file
* @param {Object} data
* @returns {*}
*/
public renderViewFromEngine(file: string, data?: any): any {
const view = $.path.engine("backend/views/" + file);
return this.renderView(view, data, true, true);
}
/**
* Implement InXpresserError try method
* @param fn
* @param log
*/
public try<T = unknown>(fn: () => T, log: boolean = true): T {
return InXpresserError.tryOrCatch(fn, e => log ? this.$instance().logError(e) : void 0);
}
/**
* Implement InXpresserError tryOrCatch method
* @param fn
* @param handleError
*/
public tryOrCatch<T = unknown>(fn: () => T, handleError?: (error: InXpresserError) => any): T {
return InXpresserError.tryOrCatch(fn, handleError);
}
/**
* Throw error as type of InXpresserError
* @param e
* @param log
*/
public throw(e: Error, log: boolean = true): never {
e = InXpresserError.use(e);
if (log) $.logError(e);
throw e;
}
/**
* Send Message to view
* @param {Object|string} data
* @param {*} value
* @returns {RequestEngine}
*/
public with(data: any, value = null): this {
if (this.req.flash) {
if (typeof data === "string") {
this.req.flash(data, value);
} else {
const dataKeys = Object.keys(data);
for (let i = 0; i < dataKeys.length; i++) {
this.req.flash(dataKeys[i], data[dataKeys[i]]);
}
}
}
return this;
}
/**
* Return old values to view after redirect
* @returns {RequestEngine}
*/
public withOld(): this {
if (this.req.flash) {
const data = this.all();
const dataKeys = Object.keys(data);
for (let i = 0; i < dataKeys.length; i++) {
this.req.flash("old:" + dataKeys[i], data[dataKeys[i]]);
}
}
return this;
}
/**
* End Request Signal
*/
public end() {
return "EndCurrentRequest";
}
/**
* Shorthand function for adding data to the `boot.*` state
*/
addToBoot(name: string, value: any) {
this.state.set(`boot.${name}`, value);
return this;
}
}
export = RequestEngine;