UNPKG

2.31 kBJavaScriptView Raw
1"use strict"
2
3const contextService = require('request-context')
4const debug = require("debug")("motif:context")
5
6class Context {
7 get port() {
8 return this._port
9 }
10
11 get config() {
12 return this._config
13 }
14
15 get process() {
16 return this._motif
17 }
18
19 get constants() {
20 return this._motif.constants || {}
21 }
22
23 get appPath() {
24 return this._appPath
25 }
26
27 get docPath() {
28 return this._config.docPath
29 }
30
31 get interfaceVersion() {
32 return this._interfaceVersion
33 }
34
35 get path() {
36 return this._path
37 }
38
39 get createDoc() {
40 return this._createDoc
41 }
42
43 get useCookie() {
44 return this._useCookie
45 }
46
47 get useProxy() {
48 return this._useProxy
49 }
50
51 get session() {
52 return this._session
53 }
54
55 get request() {
56 return contextService.get('request:req')
57 }
58
59 get userAgent() {
60 return contextService.get('request:ua')
61 }
62
63 get prefix() {
64 return this._prefix
65 }
66
67 get initMode() {
68 return this._initMode
69 }
70
71 _normalizePath(val) {
72 if (val && val.indexOf("/") === 0) {
73 return val.substr(1)
74 }
75
76 return val
77 }
78
79 _normalizePort(val) {
80 let port = parseInt(val, 10)
81 if (isNaN(port)) {
82 return val
83 }
84
85 if (port >= 0) {
86 return port
87 }
88
89 return false
90 }
91
92 constructor(options) {
93 let {
94 motif,
95 appPath,
96 config,
97 constants,
98 interfaceVersion,
99 path,
100 port,
101 createDoc,
102 autoCreate,
103 useFavicon,
104 useProxy,
105 useCookie,
106 session,
107 prefix
108 } = options
109
110 debug("context", options)
111
112 this._initMode = autoCreate === true || process.argv.includes('--init') ? true : false
113 this._motif = motif
114 this._appPath = appPath
115 this._config = config
116 this._constants = constants
117 this._interfaceVersion = interfaceVersion || "v1"
118 this._path = this._normalizePath(path || "")
119 this._port = this._normalizePort(port || config && config.port || 3000)
120 this._createDoc = createDoc === true ? true : (config && config.createDoc || false)
121 this._useFavicon = useFavicon === true ? true : false
122 this._useCookie = useCookie === true ? true : false
123 this._useProxy = useProxy === true ? true : false
124 this._session = session || null
125 this._prefix = prefix || 'motif'
126 }
127}
128
129module.exports = Context