1 | process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
|
2 | import 'reflect-metadata'
|
3 | import {Container} from 'inversify'
|
4 | import {getConnectionManager, Connection, BaseEntity, getRepository, SelectQueryBuilder} from '@bxjs/typeorm'
|
5 | import {xsession, xuser, xcache} from './session'
|
6 | import * as $$ from './plugins'
|
7 |
|
8 | const path = require('path')
|
9 | const ErrorStackParser = require('error-stack-parser')
|
10 | const cookie = require('cookie')
|
11 | const MobileDetect = require('mobile-detect')
|
12 | const fetch = require('node-fetch')
|
13 | const _ = require('lodash')
|
14 | const moment = require('moment')
|
15 | const extend = require('extend')
|
16 | const querystring = require('querystring')
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 | const circular_json = require("circular-json")
|
26 | const mockjs = require('mockjs')
|
27 | const shortid = require('shortid')
|
28 | const validatorjs = require('validatorjs')
|
29 | const cross_spawn = require('cross-spawn')
|
30 | const ACMClient = require('acm-client')
|
31 | const co = require('co')
|
32 |
|
33 |
|
34 | const raw_stringify = JSON.stringify
|
35 |
|
36 | function new_stringify(value: any, replacer?: (key: string, value: any) => any,
|
37 | space?: string | number): string {
|
38 | let out = raw_stringify(value, replacer, space)
|
39 | if (_.isString(out)) {
|
40 | out = out.replace(/\\n/g, '\\\\n')
|
41 | .replace(/\\t/g, '\\\\t')
|
42 | .replace(/\\u/g, '\\\\u')
|
43 | }
|
44 | return out
|
45 | }
|
46 |
|
47 | JSON.stringify = new_stringify as any
|
48 |
|
49 |
|
50 | export function get_suffix_ts_or_js() {
|
51 | if (global['__env__'] == 'local' && !/^\/code\/node_modules/.test(__dirname)) {
|
52 | return 'ts'
|
53 | } else {
|
54 | return 'js'
|
55 | }
|
56 | }
|
57 |
|
58 |
|
59 | function __get_base_func_caller_source_position(position: number = 3) {
|
60 | try {
|
61 | throw new Error()
|
62 | } catch (err) {
|
63 | let out = ErrorStackParser.parse(err)
|
64 | let idx = 0
|
65 |
|
66 | let find_ts_sufix_file_count = 0
|
67 | for (; idx < out.length; idx++) {
|
68 | if (/\.ts$/.test(out[idx].fileName)) {
|
69 | find_ts_sufix_file_count += 1
|
70 | }
|
71 | if (find_ts_sufix_file_count == position) {
|
72 | break
|
73 | }
|
74 | }
|
75 | if (find_ts_sufix_file_count == position) {
|
76 | return '[' + out[idx]['fileName'] + ':' + out[idx]['lineNumber'] + ']'
|
77 | } else {
|
78 |
|
79 |
|
80 | console.error(circular_json.stringify(out, null, 4)
|
81 | .replace(/\r/g, '').replace(/\n/g, ''))
|
82 | return '#'
|
83 | }
|
84 |
|
85 | }
|
86 | }
|
87 |
|
88 |
|
89 | export function xstack(err, compact = true) {
|
90 | try {
|
91 |
|
92 | let stack = ErrorStackParser.parse(err)
|
93 | if (compact) {
|
94 | let sources: string[] = []
|
95 | for (let v of stack) {
|
96 | sources.push(`${v['fileName']}:${v['lineNumber']}`)
|
97 | }
|
98 | return sources
|
99 | }
|
100 | return stack
|
101 | } catch (err1) {
|
102 | let source = __get_base_func_caller_source_position()
|
103 | return `invalid error input param (${source})`
|
104 | }
|
105 | }
|
106 |
|
107 |
|
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 | export function xerror(err, __param?: any) {
|
119 | xassert(err instanceof Error)
|
120 | try {
|
121 |
|
122 | let data: any = JSON.parse(err.message)
|
123 | if (data.code && data.msg && ERRORS[data.code]) {
|
124 | return data
|
125 | }
|
126 | } catch (err) {
|
127 |
|
128 | }
|
129 |
|
130 | let msg = ERRORS[ERR$UNKNOWN]['zh']
|
131 | let code = ERR$UNKNOWN
|
132 | let param: any = {msg: err.message, param: __param}
|
133 | let stack = xstack(err)
|
134 | let data = {msg, code, param, stack}
|
135 | return data
|
136 | }
|
137 |
|
138 |
|
139 | export function xroot(err: Error) {
|
140 | xassert(err instanceof Error)
|
141 | let {msg, param, code, stack} = xerror(err)
|
142 |
|
143 |
|
144 | for (; param && param.msg;) {
|
145 | try {
|
146 | let json: any = JSON.parse(param.msg)
|
147 | param = json.param
|
148 | } catch (err) {
|
149 | msg = param.msg
|
150 | code = param.code
|
151 | stack = param.stack
|
152 | param = param.param
|
153 | break
|
154 | }
|
155 | }
|
156 | return {msg, code, param, stack}
|
157 | }
|
158 |
|
159 |
|
160 |
|
161 |
|
162 |
|
163 |
|
164 |
|
165 |
|
166 |
|
167 |
|
168 |
|
169 |
|
170 |
|
171 |
|
172 | export function xthrow(code: string | Error = ERR$UNKNOWN, param: any = undefined, reject_param: any = undefined) {
|
173 |
|
174 | let reject: any = _.isFunction(param) ? param : undefined
|
175 | if (reject) param = reject_param
|
176 | let data: any = {}
|
177 | let source = __get_base_func_caller_source_position()
|
178 |
|
179 | if (code instanceof Error) {
|
180 | try {
|
181 | data = JSON.parse(code.message)
|
182 |
|
183 | if (!_.isArray(data.stack)) {
|
184 | data.stack = []
|
185 | }
|
186 | data.stack.push(source)
|
187 | } catch (err) {
|
188 |
|
189 | }
|
190 |
|
191 | if (data.code && data.msg && ERRORS[data.code]) {
|
192 |
|
193 | if (_.isFunction(reject)) {
|
194 |
|
195 | let err = new Error(JSON.stringify(data))
|
196 | reject(err)
|
197 | return
|
198 | } else {
|
199 | throw new Error(JSON.stringify(data))
|
200 | }
|
201 | }
|
202 |
|
203 | data = xerror(code, param)
|
204 | data.code = ERR$UNKNOWN
|
205 | data.msg = ERRORS[ERR$UNKNOWN]['zh']
|
206 | data.param = {msg: code.message, param, stack: [source]}
|
207 | } else {
|
208 |
|
209 | data = {code, msg: global['ERRORS'][code as string]['zh'], param, stack: [source]}
|
210 | }
|
211 |
|
212 |
|
213 | if (_.isFunction(reject)) {
|
214 |
|
215 | reject(new Error(JSON.stringify(data)))
|
216 | } else {
|
217 |
|
218 | throw new Error(JSON.stringify(data))
|
219 | }
|
220 | }
|
221 |
|
222 | export function xassert(expr: any, code: string = ERR$ASSERT, param?: any) {
|
223 | let source = __get_base_func_caller_source_position()
|
224 | let stack = [source]
|
225 | if (!expr) throw new Error(JSON.stringify({code, msg: global['ERRORS'][code]['zh'], param, stack}))
|
226 | return expr
|
227 | }
|
228 |
|
229 |
|
230 |
|
231 |
|
232 |
|
233 |
|
234 |
|
235 |
|
236 |
|
237 |
|
238 |
|
239 |
|
240 | export function xlog(...args) {
|
241 |
|
242 | let source = __get_base_func_caller_source_position() + '[' + xnow('YYYY-MM-DD HH:mm:ss.SSS') + ']'
|
243 | let output = circular_json.stringify([...args], null, 4)
|
244 | if (global['__env__'] != 'prod' && !/^\/code\/node_modules/.test(__dirname)) {
|
245 |
|
246 | console.log.apply(undefined, [source + output])
|
247 |
|
248 | const fs = require('fs')
|
249 | const logFilePath = process.env['NODE_LOGFILE'] ? process.env['NODE_LOGFILE'] : '/tmp/bxjs.log'
|
250 | fs.appendFileSync(logFilePath, source + output + "\r\n")
|
251 | } else {
|
252 |
|
253 |
|
254 | output = output.replace(/\r/g, '').replace(/\n/g, '')
|
255 | console.log.apply(undefined, [source + output])
|
256 | }
|
257 | }
|
258 |
|
259 |
|
260 |
|
261 |
|
262 |
|
263 |
|
264 |
|
265 |
|
266 |
|
267 |
|
268 |
|
269 | async function xwarn(...args) {
|
270 |
|
271 | let source = __get_base_func_caller_source_position()
|
272 |
|
273 |
|
274 | if (args.length > 0 && args[0] instanceof Error) {
|
275 | args[0] = xerror(args[0])
|
276 | }
|
277 |
|
278 | let out = [source, xnow('YYYY-MM-DD HH:mm:ss.SSS'), {...args}]
|
279 |
|
280 |
|
281 | let access_token = xconfig('framework.warn.dingding.access_token')
|
282 | let mobiles = xconfig('framework.warn.dingding.mobiles')
|
283 | if (!access_token || !mobiles) {
|
284 | access_token = '020a09eac5f2fa320ae851442d5e19e23693c64ad2255c85354b4a49a5a48d35'
|
285 | mobiles = ['15381151346']
|
286 | }
|
287 |
|
288 | await xpost(`https://oapi.dingtalk.com/robot/send?access_token=${access_token}`, {
|
289 | msgtype: 'text',
|
290 | text: {
|
291 | content: out
|
292 | },
|
293 | at: {
|
294 | atMobiles: mobiles,
|
295 | isAtAll: false
|
296 | }
|
297 | })
|
298 |
|
299 |
|
300 |
|
301 | xlog(out)
|
302 | }
|
303 |
|
304 |
|
305 | process.on('uncaughtException', async function (err) {
|
306 | xlog(xerror(err))
|
307 | await xwarn(err)
|
308 | process.exit(-1)
|
309 | })
|
310 |
|
311 |
|
312 | process.on('unhandledRejection', async (reason, p) => {
|
313 | xlog('Unhandled Rejection at: Promise', p, 'reason:', reason);
|
314 |
|
315 | await xwarn(reason, p)
|
316 | process.exit(-1)
|
317 | })
|
318 |
|
319 |
|
320 | const sleep = require('sleep-async')()
|
321 |
|
322 | export function xsleep(ms: number = -1) {
|
323 | if (ms <= 0) {
|
324 | ms = 50 * 365 * 24 * 3600 * 1000
|
325 | }
|
326 | return new Promise((resolve, reject) => {
|
327 | try {
|
328 | sleep.sleep(ms, () => {
|
329 | resolve()
|
330 | })
|
331 | } catch (err) {
|
332 | xlog(xerror(err))
|
333 | resolve()
|
334 |
|
335 | }
|
336 | })
|
337 | }
|
338 |
|
339 | export async function xpost(url: string, param?: { [propName: string]: any },
|
340 | headers?: { [propName: string]: any }, timeout: number = 3000) {
|
341 |
|
342 | timeout = 5000
|
343 | let res: any = null
|
344 | let json: any = null
|
345 | let text: any = null
|
346 | try {
|
347 | res = await fetch(url, {
|
348 | method: 'POST',
|
349 | body: JSON.stringify(param),
|
350 | headers: {'Content-Type': 'application/json', ...headers},
|
351 | timeout: timeout <= 0 ? 0 : timeout,
|
352 | })
|
353 | text = await res.text()
|
354 | json = JSON.parse(text)
|
355 | return json
|
356 | } catch (err) {
|
357 | xthrow(err, {url, param, headers, text})
|
358 | }
|
359 | }
|
360 |
|
361 |
|
362 | export async function xget(url: string, param?: { [propName: string]: any },
|
363 | headers?: { [propName: string]: any }, timeout: number = 3000) {
|
364 |
|
365 | timeout = 5000
|
366 | let res: any = null
|
367 | let json: any = null
|
368 | let text: any = null
|
369 | try {
|
370 | url = url + (param ? '?' : '') + querystring.stringify(param)
|
371 | res = await fetch(url, {
|
372 | method: 'GET',
|
373 | headers: {'Content-Type': 'application/json', ...headers},
|
374 | timeout: timeout <= 0 ? 0 : timeout,
|
375 | })
|
376 | text = await res.text()
|
377 | json = JSON.parse(text)
|
378 | return json
|
379 | } catch (err) {
|
380 | xthrow(err, {url, param, headers, text})
|
381 | }
|
382 | }
|
383 |
|
384 |
|
385 | export function xredirect(url: string, param: any = {}) {
|
386 |
|
387 |
|
388 | xassert(global['__redirect_url__'] === undefined)
|
389 | if (param) {
|
390 | xassert(_.isPlainObject(param))
|
391 |
|
392 | delete param.__api__
|
393 | delete param.__url__
|
394 |
|
395 | if (/\?/.test(url)) {
|
396 | url += '&'
|
397 | } else {
|
398 | url += '?'
|
399 | }
|
400 | url += querystring.stringify(param)
|
401 | }
|
402 | global['__redirect_url__'] = url
|
403 | }
|
404 |
|
405 |
|
406 | export function xcookie(key?: string, value?: string, option?: {}): any {
|
407 | if (!arguments.length) {
|
408 |
|
409 | return global['__request_cookies__'] ? global['__request_cookies__'] : {}
|
410 | } else if (arguments.length == 1) {
|
411 | return key ? xcookie()[key] : undefined
|
412 | } else {
|
413 | if (global['__respond_cookies__'] === undefined) {
|
414 | global['__respond_cookies__'] = {}
|
415 | }
|
416 | if (key) {
|
417 |
|
418 | option = xassign({path: '/', maxAge: 24 * 3600}, option)
|
419 | global['__respond_cookies__'][key] = cookie.serialize(key, value, option)
|
420 | }
|
421 | return
|
422 | }
|
423 | }
|
424 |
|
425 |
|
426 | function xismobile(): boolean {
|
427 | const md = new MobileDetect(global['__user_agent__'])
|
428 | return !!md.mobile()
|
429 | }
|
430 |
|
431 | function xassign(target, source, ...args) {
|
432 | const param = [true, target, source, ...args]
|
433 | return extend.apply(null, param)
|
434 | }
|
435 |
|
436 |
|
437 | function xconfig(path: string, defaultValue: any = undefined) {
|
438 | if (global['__config__']) {
|
439 | return _.get(global['__config__'], path, defaultValue)
|
440 | }
|
441 |
|
442 | const fp = require('path')
|
443 | const fs = require('fs')
|
444 |
|
445 | let config_path = ''
|
446 | if (__dirname.includes('/node_modules/@bxjs/base/')) {
|
447 |
|
448 | config_path = fp.join(__dirname, '../../../../app/config')
|
449 | } else {
|
450 |
|
451 | config_path = fp.join(__dirname, '../app/config')
|
452 | }
|
453 |
|
454 |
|
455 | const config_base_path = config_path + '/config.base.' + get_suffix_ts_or_js()
|
456 | const config_env_path = config_path + `/config.${global['__env__']}.` + get_suffix_ts_or_js()
|
457 | if (!fs.existsSync(config_base_path)) {
|
458 | return defaultValue
|
459 | }
|
460 | let config_base = require(config_base_path).default
|
461 | let config_env = {}
|
462 | if (fs.existsSync(config_env_path)) {
|
463 | config_env = require(config_env_path).default
|
464 | }
|
465 |
|
466 |
|
467 |
|
468 | global['__config__'] = xassign({}, config_base, config_env)
|
469 | return _.get(global['__config__'], path, defaultValue)
|
470 | }
|
471 |
|
472 | async function xconnect(callback: (connect: Connection) => Promise<any>, config = 'default') {
|
473 | return new Promise(async (resolve, reject) => {
|
474 | let cfg = {} as any
|
475 | try {
|
476 | cfg = xassign({}, xconfig('plugins.database.default', {}))
|
477 | xassert(!_.isEmpty(cfg), ERR$PARAM, {config})
|
478 |
|
479 | if (__dirname.includes('/node_modules/@bxjs/base/')) {
|
480 |
|
481 | cfg['entities'] = [
|
482 | path.join(__dirname, '../../../../app/plugins/database/entity/*.' + get_suffix_ts_or_js())
|
483 | ]
|
484 | } else {
|
485 |
|
486 | cfg['entities'] = [
|
487 | path.join(__dirname, '../app/plugins/database/entity/*.' + get_suffix_ts_or_js())
|
488 | ]
|
489 | }
|
490 |
|
491 | const mng = getConnectionManager()
|
492 | const name = cfg.name ? cfg.name : 'default'
|
493 | if (!mng.has(name)) {
|
494 | mng.create(cfg)
|
495 | }
|
496 | const db = mng.get(name)
|
497 | if (global['g_connection'] === undefined) {
|
498 | global['g_connection'] = {}
|
499 | }
|
500 | if (!db.isConnected) {
|
501 | global['g_connection'][name] = db.connect()
|
502 | }
|
503 | await global['g_connection'][name].then(async connection => {
|
504 | xassert(db.isConnected)
|
505 | const out = await callback(connection)
|
506 |
|
507 | resolve(out)
|
508 | }).catch(async err => {
|
509 |
|
510 | xthrow(err, reject, {cfg})
|
511 | })
|
512 | } catch (err) {
|
513 | xthrow(err, reject, {cfg})
|
514 | }
|
515 | })
|
516 | }
|
517 |
|
518 |
|
519 | function xnew<T extends BaseEntity>(TYPE: new () => T, param?: any, ...args): T {
|
520 |
|
521 |
|
522 |
|
523 |
|
524 |
|
525 | let obj = new TYPE()
|
526 | if (_.isEmpty(param)) {
|
527 | return obj
|
528 | }
|
529 | let repo = getRepository<T>(TYPE)
|
530 | repo.merge.apply(repo, [obj, param, ...args])
|
531 | return obj
|
532 | }
|
533 |
|
534 |
|
535 | function xquery<T>(connect: Connection, TYPE: new () => T, alias?: string): SelectQueryBuilder<T> {
|
536 | return connect.getRepository(TYPE).createQueryBuilder(alias)
|
537 | }
|
538 |
|
539 |
|
540 | async function xcount<T>(sql: SelectQueryBuilder<T>, page: number, size: number): Promise<[any[] | null, number]> {
|
541 | xassert(page >= 1)
|
542 | const [count, rows] = await Promise.all([
|
543 | sql.getCount(),
|
544 | sql.offset((page - 1) * size).limit(size).getRawMany()
|
545 | ])
|
546 | return [rows, count]
|
547 | }
|
548 |
|
549 |
|
550 |
|
551 |
|
552 | function xroute(param: { name?: string, desc?: string, path?: string, auth?: boolean }) {
|
553 |
|
554 | param = xassign({name: '', desc: '', path: '', auth: true}, param)
|
555 | return function (target: Function, propertyKey: string, descriptor: PropertyDescriptor) {
|
556 |
|
557 |
|
558 | target.prototype.context = () => {
|
559 | return {
|
560 | param: param,
|
561 |
|
562 | auth: async () => {
|
563 |
|
564 | if (param && param.auth) {
|
565 |
|
566 |
|
567 | const auth = xgot(YAuth)
|
568 | xassert(await auth.getLoginStatus(), ERR$UNAUTHORIZED)
|
569 | }
|
570 | }
|
571 | }
|
572 | }
|
573 | }
|
574 | }
|
575 |
|
576 |
|
577 |
|
578 |
|
579 |
|
580 |
|
581 |
|
582 |
|
583 |
|
584 |
|
585 |
|
586 |
|
587 |
|
588 |
|
589 |
|
590 | function xmock<T>(rules: T): any {
|
591 | return mockjs.mock(rules)
|
592 | }
|
593 |
|
594 | function xrandom(name: string, data: any[]) {
|
595 | mockjs.Random.extend({
|
596 | [name]: (...args) => {
|
597 | xassert(data.length > 0)
|
598 | if (data.length == 1) return data[0]
|
599 | let max = data.length - 1
|
600 | let idx = xmock(`@int(0,${max})`)
|
601 | return data[idx]
|
602 | }
|
603 | })
|
604 | }
|
605 |
|
606 |
|
607 | mockjs.Random.extend({
|
608 |
|
609 | id: (...args) => {
|
610 | return shortid.generate()
|
611 | },
|
612 |
|
613 | mobile: (...args) => {
|
614 | const isps = [
|
615 | 134, 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 182, 183, 184, 187, 188, 178,
|
616 | 130, 131, 132, 145, 155, 156, 185, 186, 176,
|
617 | 133, 134, 153, 180, 181, 189, 177, 173,
|
618 | 176, 173, 177, 178, 170,
|
619 | 140, 141, 142, 143, 144, 146, 148, 149, 154]
|
620 | let max = isps.length - 1
|
621 | let idx = xmock(`@int(0,${max})`)
|
622 | let num = xmock(`@int(100000000,199999999)`)
|
623 | return (isps[idx] * 100000000 + num % 100000000) + ''
|
624 | },
|
625 |
|
626 | paragraph: (...args) => {
|
627 | switch (args.length) {
|
628 | case 0:
|
629 | return xmock('@cparagraph')
|
630 | case 1:
|
631 | return xmock(`@cparagraph(${args[0]})`)
|
632 | case 2:
|
633 | return xmock(`@cparagraph(${args[0]},${args[1]})`)
|
634 | default:
|
635 | xassert(false)
|
636 | }
|
637 |
|
638 | },
|
639 | sentence: (...args) => {
|
640 | switch (args.length) {
|
641 | case 0:
|
642 | return xmock('@csentence')
|
643 | case 1:
|
644 | return xmock(`@csentence(${args[0]})`)
|
645 | case 2:
|
646 | return xmock(`@csentence(${args[0]},${args[1]})`)
|
647 | default:
|
648 | xassert(false)
|
649 | }
|
650 |
|
651 | },
|
652 | title: (...args) => {
|
653 | switch (args.length) {
|
654 | case 0:
|
655 | return xmock('@ctitle')
|
656 | case 1:
|
657 | return xmock(`@ctitle(${args[0]})`)
|
658 | case 2:
|
659 | return xmock(`@ctitle(${args[0]},${args[1]})`)
|
660 | default:
|
661 | xassert(false)
|
662 | }
|
663 |
|
664 | },
|
665 | })
|
666 |
|
667 |
|
668 | function xcheck<T>(param: T, rules: T, messages?: Object) {
|
669 | let obj = new validatorjs(param, rules)
|
670 | if (obj.fails()) {
|
671 | xthrow(ERR$PARAM, obj.errors)
|
672 | }
|
673 | }
|
674 |
|
675 |
|
676 | function xbind<T>(TYPE: new () => T) {
|
677 | const o: any = new TYPE()
|
678 | return xcontainer.bind<T>(o.id).to(require(`@app/plugins/${o.id}`).default)
|
679 | }
|
680 |
|
681 |
|
682 | function xgot<T>(TYPE: new () => T) {
|
683 | const o: any = new TYPE()
|
684 | return xcontainer.get<T>(o.id)
|
685 | }
|
686 |
|
687 |
|
688 | async function xcmd(...args: string[]): Promise<any> {
|
689 | try {
|
690 | const options: any = {}
|
691 | options.cwd = options.cwd || process.env.__ctxPath || process.cwd();
|
692 | xassert(_.isArray(args) && args.length > 0)
|
693 | const cmd = args.shift()
|
694 | const ret = cross_spawn.sync(cmd, args, xassign({stdio: 'inherit'}, options))
|
695 | xassert(ret.status === 0, ERR$UNKNOWN, ret)
|
696 | return ret
|
697 | } catch (err) {
|
698 | await xwarn(err)
|
699 | xthrow(err)
|
700 | }
|
701 | }
|
702 |
|
703 |
|
704 | async function xmap<T>(values: T[], callack: (v: T) => Promise<any>): Promise<any[]> {
|
705 | xassert(_.isArray(values) && _.isFunction(callack))
|
706 | return Promise.all(values.map(callack))
|
707 | }
|
708 |
|
709 |
|
710 |
|
711 | async function xacm(group: string, id: string) {
|
712 | const cfg = xconfig(`plugins.acm`)
|
713 | xassert(group && cfg && cfg[group], ERR$CONFIG, {cfg})
|
714 | const acm = new ACMClient(cfg[group])
|
715 | return new Promise(async (resolve, reject) => {
|
716 | try {
|
717 | co(function* () {
|
718 | try {
|
719 | group = group + ':' + global['__env__']
|
720 | const content = yield acm.getConfig(id, group)
|
721 | xassert(content, ERR$CONFIG, {id, group})
|
722 | resolve(content)
|
723 | } catch (err) {
|
724 | xthrow(err, reject, {id, group, cfg: cfg[group]})
|
725 | }
|
726 | });
|
727 | } catch (err) {
|
728 | xthrow(err, reject, {id, group, cfg: cfg[group]})
|
729 | }
|
730 | })
|
731 | }
|
732 |
|
733 |
|
734 | function xnow(format = 'YYYY-MM-DD HH:mm:ss') {
|
735 | return moment().utcOffset(8).format(format)
|
736 | }
|
737 |
|
738 |
|
739 | function xbase64encode(value: string) {
|
740 | xassert(!_.isEmpty(value) && _.isString(value))
|
741 | return new Buffer(value).toString('base64')
|
742 | }
|
743 |
|
744 |
|
745 | function xbase64decode(value: string) {
|
746 | xassert(!_.isEmpty(value) && _.isString(value))
|
747 | return new Buffer(value, 'base64').toString()
|
748 | }
|
749 |
|
750 |
|
751 | function xreset() {
|
752 |
|
753 | for (let key of Object.keys(global)) {
|
754 | if (key.startsWith('__') && key.endsWith('__')) {
|
755 | global[key] = undefined
|
756 | }
|
757 | }
|
758 |
|
759 | if (!global['__env__']) {
|
760 | global['__env__'] = 'local'
|
761 | }
|
762 | global['__config__'] = undefined
|
763 | global['__session__'] = {}
|
764 | global['__cache__'] = {}
|
765 | global['__user__'] = {}
|
766 | global['__user_agent__'] = undefined
|
767 | global['__client_ip__'] = undefined
|
768 | global['__redirect_url__'] = undefined
|
769 | global['__request_cookies__'] = {}
|
770 | global['__respond_cookies__'] = {}
|
771 | }
|
772 |
|
773 |
|
774 | xreset()
|
775 |
|
776 | global['xreset'] = xreset
|
777 | global['xconnect'] = xconnect
|
778 | global['xnew'] = xnew
|
779 | global['xquery'] = xquery
|
780 | global['xcount'] = xcount
|
781 | global['xassign'] = xassign
|
782 | global['xconfig'] = xconfig
|
783 | global['xthrow'] = xthrow
|
784 | global['xassert'] = xassert
|
785 | global['xerror'] = xerror
|
786 | global['xroot'] = xroot
|
787 | global['xstack'] = xstack
|
788 | global['xwarn'] = xwarn
|
789 | global['xlog'] = xlog
|
790 | global['xpost'] = xpost
|
791 | global['xget'] = xget
|
792 | global['xsleep'] = xsleep
|
793 | global['xredirect'] = xredirect
|
794 | global['xcookie'] = xcookie
|
795 | global['xismobile'] = xismobile
|
796 | global['xsession'] = xsession
|
797 | global['xuser'] = xuser
|
798 | global['xcache'] = xcache
|
799 | global['xroute'] = xroute
|
800 | global['xmock'] = xmock
|
801 | global['xrandom'] = xrandom
|
802 | global['xcheck'] = xcheck
|
803 | global['xcontainer'] = new Container()
|
804 | global['xbind'] = xbind
|
805 | global['xgot'] = xgot
|
806 | global['YAuth'] = $$.YAuth
|
807 | global['xcmd'] = xcmd
|
808 | global['xmap'] = xmap
|
809 | global['xacm'] = xacm
|
810 | global['xbase64encode'] = xbase64encode
|
811 | global['xbase64decode'] = xbase64decode
|
812 | global['xnow'] = xnow
|