oox 0.3.0-beta11 → 0.3.0-beta13

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.
@@ -1,192 +1,192 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HTTPConfig = void 0;
4
- const http = require("node:http");
5
- const node_querystring_1 = require("node:querystring");
6
- const utils_1 = require("./utils");
7
- const oox = require("../../index");
8
- const module_1 = require("../module");
9
- class HTTPConfig extends module_1.ModuleConfig {
10
- // listen port
11
- port = 0;
12
- // service path
13
- path = '/';
14
- // browser cross origin
15
- origin = '';
16
- }
17
- exports.HTTPConfig = HTTPConfig;
18
- class HTTPModule extends module_1.default {
19
- name = 'http';
20
- config = new HTTPConfig;
21
- server = null;
22
- setConfig(config) {
23
- Object.assign(this.config, config);
24
- if (!config.hasOwnProperty('port')) {
25
- this.config.port = oox.config.port;
26
- }
27
- if (!config.hasOwnProperty('origin')) {
28
- this.config.origin = oox.config.origin;
29
- }
30
- }
31
- getConfig() {
32
- return this.config;
33
- }
34
- /**
35
- * start http service
36
- */
37
- async serve() {
38
- await this.stop();
39
- const { port } = this.config;
40
- this.server = http.createServer(this.call.bind(this));
41
- this.server.listen(port);
42
- const address = this.server.address();
43
- if (!address || 'object' !== typeof address)
44
- throw new Error('Cannot read http server port');
45
- this.config.port = address.port;
46
- }
47
- /**
48
- * stop http service
49
- */
50
- stop() {
51
- if (this.server && this.server.listening)
52
- return new Promise((resolve, reject) => {
53
- this.server.close(function (error) {
54
- if (error)
55
- reject(error);
56
- else
57
- resolve();
58
- });
59
- });
60
- }
61
- /**
62
- * browser cross origin
63
- */
64
- cors(request, response) {
65
- // origin checking
66
- const origin = this.config.origin;
67
- const requestOrigin = request.headers.origin;
68
- if (origin && requestOrigin) {
69
- if (origin === '*' || origin === requestOrigin || Array.isArray(origin) && origin.includes(requestOrigin)) {
70
- response.setHeader('Access-Control-Allow-Origin', requestOrigin);
71
- response.setHeader('Vary', 'Origin');
72
- }
73
- else {
74
- response.statusCode = 403;
75
- response.end();
76
- return false;
77
- }
78
- response.setHeader('Access-Control-Max-Age', 3600);
79
- response.setHeader('Access-Control-Allow-Headers', 'x-caller,content-type');
80
- response.setHeader('Access-Control-Allow-Methods', '*');
81
- }
82
- if (request.method === 'OPTIONS') {
83
- response.statusCode = 204;
84
- response.end();
85
- return false;
86
- }
87
- return true;
88
- }
89
- /**
90
- * HTTP-RPC服务器请求监听方法
91
- */
92
- async call(request, response) {
93
- if (request.url !== this.config.path) {
94
- const error = {
95
- message: 'Invalid URL',
96
- stack: ''
97
- };
98
- Error.captureStackTrace(error);
99
- return this.respond(request, response, {
100
- success: false,
101
- error
102
- });
103
- }
104
- if (!this.cors(request, response))
105
- return;
106
- let body = Object.create(null);
107
- try {
108
- if ('GET' === request.method) {
109
- body = (0, node_querystring_1.parse)(request.url.split('?').pop());
110
- }
111
- else {
112
- body = await (0, utils_1.parseHTTPBody)(request);
113
- }
114
- if (!body || 'object' !== typeof body)
115
- throw new Error('Content Invalid');
116
- }
117
- catch (error) {
118
- return this.respond(request, response, {
119
- success: false,
120
- error: {
121
- message: error.message,
122
- stack: error.stack
123
- }
124
- });
125
- }
126
- // global unique id
127
- const traceId = String(request.headers['x-trace-id'] || '');
128
- // service name, required
129
- const caller = String(request.headers['x-caller'] || 'anonymous');
130
- // client ip or caller service ip
131
- const ip = String(request.headers['x-ip'] || request.socket.remoteAddress || '');
132
- // startup client ip
133
- const sourceIP = String(request.headers['x-real-ip'] || '');
134
- const { action = 'index', params = [] } = body;
135
- const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
136
- const format = await oox.call(action, params, context);
137
- this.respond(request, response, format);
138
- }
139
- /**
140
- * HTTP Response Catch
141
- */
142
- respond(request, response, format) {
143
- let formatString = '';
144
- try {
145
- formatString = JSON.stringify(format);
146
- }
147
- catch ({ message, stack }) {
148
- delete format.body;
149
- format.success = false;
150
- format.error = {
151
- message,
152
- stack
153
- };
154
- formatString = JSON.stringify(format);
155
- }
156
- response.setHeader('Content-Type', 'application/json');
157
- response.setHeader('Content-Length', Buffer.byteLength(formatString));
158
- response.end(formatString);
159
- }
160
- /**
161
- * HTTP RPC
162
- */
163
- async rpc(url, action, params, context) {
164
- if (!context || !context.traceId) {
165
- context = oox.getContext();
166
- }
167
- const { traceId, caller, sourceIP } = context;
168
- const headers = {
169
- 'Content-Type': 'application/json',
170
- 'x-trace-id': String(traceId),
171
- };
172
- if (caller)
173
- headers['x-caller'] = String(caller);
174
- if (sourceIP)
175
- headers['x-real-ip'] = sourceIP;
176
- // headers [ 'x-ip' ] = getIPAddress ( 4 ) [ 0 ]
177
- const format = await (0, utils_1.httpRequest)(url, {
178
- headers
179
- }, JSON.stringify({ action, params }));
180
- if ('string' === typeof format)
181
- throw new Error(format);
182
- const { error, body } = format;
183
- if (error) {
184
- const asyncError = new Error(error.message);
185
- throw asyncError;
186
- }
187
- else {
188
- return body;
189
- }
190
- }
191
- }
192
- exports.default = HTTPModule;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HTTPConfig = void 0;
4
+ const http = require("node:http");
5
+ const node_querystring_1 = require("node:querystring");
6
+ const utils_1 = require("./utils");
7
+ const oox = require("../../index");
8
+ const module_1 = require("../module");
9
+ class HTTPConfig extends module_1.ModuleConfig {
10
+ // listen port
11
+ port = 0;
12
+ // service path
13
+ path = '/';
14
+ // browser cross origin
15
+ origin = '';
16
+ }
17
+ exports.HTTPConfig = HTTPConfig;
18
+ class HTTPModule extends module_1.default {
19
+ name = 'http';
20
+ config = new HTTPConfig;
21
+ server = null;
22
+ setConfig(config) {
23
+ Object.assign(this.config, config);
24
+ if (!config.hasOwnProperty('port')) {
25
+ this.config.port = oox.config.port;
26
+ }
27
+ if (!config.hasOwnProperty('origin')) {
28
+ this.config.origin = oox.config.origin;
29
+ }
30
+ }
31
+ getConfig() {
32
+ return this.config;
33
+ }
34
+ /**
35
+ * start http service
36
+ */
37
+ async serve() {
38
+ await this.stop();
39
+ const { port } = this.config;
40
+ this.server = http.createServer(this.call.bind(this));
41
+ this.server.listen(port);
42
+ const address = this.server.address();
43
+ if (!address || 'object' !== typeof address)
44
+ throw new Error('Cannot read http server port');
45
+ this.config.port = address.port;
46
+ }
47
+ /**
48
+ * stop http service
49
+ */
50
+ stop() {
51
+ if (this.server && this.server.listening)
52
+ return new Promise((resolve, reject) => {
53
+ this.server.close(function (error) {
54
+ if (error)
55
+ reject(error);
56
+ else
57
+ resolve();
58
+ });
59
+ });
60
+ }
61
+ /**
62
+ * browser cross origin
63
+ */
64
+ cors(request, response) {
65
+ // origin checking
66
+ const origin = this.config.origin;
67
+ const requestOrigin = request.headers.origin;
68
+ if (origin && requestOrigin) {
69
+ if (origin === '*' || origin === requestOrigin || Array.isArray(origin) && origin.includes(requestOrigin)) {
70
+ response.setHeader('Access-Control-Allow-Origin', requestOrigin);
71
+ response.setHeader('Vary', 'Origin');
72
+ }
73
+ else {
74
+ response.statusCode = 403;
75
+ response.end();
76
+ return false;
77
+ }
78
+ response.setHeader('Access-Control-Max-Age', 3600);
79
+ response.setHeader('Access-Control-Allow-Headers', 'x-caller,content-type');
80
+ response.setHeader('Access-Control-Allow-Methods', '*');
81
+ }
82
+ if (request.method === 'OPTIONS') {
83
+ response.statusCode = 204;
84
+ response.end();
85
+ return false;
86
+ }
87
+ return true;
88
+ }
89
+ /**
90
+ * HTTP-RPC服务器请求监听方法
91
+ */
92
+ async call(request, response) {
93
+ if (request.url !== this.config.path) {
94
+ const error = {
95
+ message: 'Invalid URL',
96
+ stack: ''
97
+ };
98
+ Error.captureStackTrace(error);
99
+ return this.respond(request, response, {
100
+ success: false,
101
+ error
102
+ });
103
+ }
104
+ if (!this.cors(request, response))
105
+ return;
106
+ let body = Object.create(null);
107
+ try {
108
+ if ('GET' === request.method) {
109
+ body = (0, node_querystring_1.parse)(request.url.split('?').pop());
110
+ }
111
+ else {
112
+ body = await (0, utils_1.parseHTTPBody)(request);
113
+ }
114
+ if (!body || 'object' !== typeof body)
115
+ throw new Error('Content Invalid');
116
+ }
117
+ catch (error) {
118
+ return this.respond(request, response, {
119
+ success: false,
120
+ error: {
121
+ message: error.message,
122
+ stack: error.stack
123
+ }
124
+ });
125
+ }
126
+ // global unique id
127
+ const traceId = String(request.headers['x-trace-id'] || '');
128
+ // service name, required
129
+ const caller = String(request.headers['x-caller'] || 'anonymous');
130
+ // client ip or caller service ip
131
+ const ip = String(request.headers['x-ip'] || request.socket.remoteAddress || '');
132
+ // startup client ip
133
+ const sourceIP = String(request.headers['x-real-ip'] || '');
134
+ const { action = 'index', params = [] } = body;
135
+ const context = oox.genContext({ traceId, caller, sourceIP, ip, callerId: '' });
136
+ const format = await oox.call(action, params, context);
137
+ this.respond(request, response, format);
138
+ }
139
+ /**
140
+ * HTTP Response Catch
141
+ */
142
+ respond(request, response, format) {
143
+ let formatString = '';
144
+ try {
145
+ formatString = JSON.stringify(format);
146
+ }
147
+ catch ({ message, stack }) {
148
+ delete format.body;
149
+ format.success = false;
150
+ format.error = {
151
+ message,
152
+ stack
153
+ };
154
+ formatString = JSON.stringify(format);
155
+ }
156
+ response.setHeader('Content-Type', 'application/json');
157
+ response.setHeader('Content-Length', Buffer.byteLength(formatString));
158
+ response.end(formatString);
159
+ }
160
+ /**
161
+ * HTTP RPC
162
+ */
163
+ async rpc(url, action, params, context) {
164
+ if (!context || !context.traceId) {
165
+ context = oox.getContext();
166
+ }
167
+ const { traceId, caller, sourceIP } = context;
168
+ const headers = {
169
+ 'Content-Type': 'application/json',
170
+ 'x-trace-id': String(traceId),
171
+ };
172
+ if (caller)
173
+ headers['x-caller'] = String(caller);
174
+ if (sourceIP)
175
+ headers['x-real-ip'] = sourceIP;
176
+ // headers [ 'x-ip' ] = getIPAddress ( 4 ) [ 0 ]
177
+ const format = await (0, utils_1.httpRequest)(url, {
178
+ headers
179
+ }, JSON.stringify({ action, params }));
180
+ if ('string' === typeof format)
181
+ throw new Error(format);
182
+ const { error, body } = format;
183
+ if (error) {
184
+ const asyncError = new Error(error.message);
185
+ throw asyncError;
186
+ }
187
+ else {
188
+ return body;
189
+ }
190
+ }
191
+ }
192
+ exports.default = HTTPModule;
@@ -1,73 +1,73 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.httpRequest = exports.parseHTTPBody = exports.stream2buffer = void 0;
4
- const http = require("node:http");
5
- /**
6
- * Stream => Buffer
7
- */
8
- function stream2buffer(stream, totalLength = 0) {
9
- return new Promise(function (resolve, reject) {
10
- let buffers = [];
11
- stream.on('error', reject);
12
- if (totalLength) {
13
- stream.on('data', function (data) { buffers.push(data); });
14
- }
15
- else {
16
- stream.on('data', function (data) {
17
- buffers.push(data);
18
- totalLength += data.length;
19
- });
20
- }
21
- stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
22
- });
23
- }
24
- exports.stream2buffer = stream2buffer;
25
- /**
26
- * Request => JSONObject
27
- */
28
- async function parseHTTPBody(request) {
29
- if (request.method === 'GET')
30
- return null;
31
- let contentType = request.headers['content-type'];
32
- // application/json; charset=utf-8
33
- if (contentType)
34
- contentType = contentType.split(';')[0].trim();
35
- const contentSize = request.headers['content-length'];
36
- const buffer = await stream2buffer(request, +contentSize || 0);
37
- if (contentSize && buffer.length !== +contentSize)
38
- throw new Error('Content-Length Incorrect');
39
- const bodyString = buffer.toString();
40
- if ('application/json' === contentType) {
41
- return JSON.parse(bodyString);
42
- }
43
- else {
44
- return bodyString;
45
- }
46
- }
47
- exports.parseHTTPBody = parseHTTPBody;
48
- /**
49
- * http request
50
- */
51
- function httpRequest(url, options, body) {
52
- return new Promise(function (resolve, reject) {
53
- const request = http.request(url, options, async function (response) {
54
- try {
55
- const result = await parseHTTPBody(response);
56
- resolve(result);
57
- }
58
- catch (error) {
59
- const decoration = new Error(`${response.statusCode} - ${error.message}`);
60
- reject(decoration);
61
- }
62
- });
63
- request.on('error', reject);
64
- if (body) {
65
- request.method = 'POST';
66
- request.setHeader('Content-Type', 'application/json');
67
- request.setHeader('Content-Length', Buffer.byteLength(body));
68
- request.write(body);
69
- }
70
- request.end();
71
- });
72
- }
73
- exports.httpRequest = httpRequest;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.httpRequest = exports.parseHTTPBody = exports.stream2buffer = void 0;
4
+ const http = require("node:http");
5
+ /**
6
+ * Stream => Buffer
7
+ */
8
+ function stream2buffer(stream, totalLength = 0) {
9
+ return new Promise(function (resolve, reject) {
10
+ let buffers = [];
11
+ stream.on('error', reject);
12
+ if (totalLength) {
13
+ stream.on('data', function (data) { buffers.push(data); });
14
+ }
15
+ else {
16
+ stream.on('data', function (data) {
17
+ buffers.push(data);
18
+ totalLength += data.length;
19
+ });
20
+ }
21
+ stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
22
+ });
23
+ }
24
+ exports.stream2buffer = stream2buffer;
25
+ /**
26
+ * Request => JSONObject
27
+ */
28
+ async function parseHTTPBody(request) {
29
+ if (request.method === 'GET')
30
+ return null;
31
+ let contentType = request.headers['content-type'];
32
+ // application/json; charset=utf-8
33
+ if (contentType)
34
+ contentType = contentType.split(';')[0].trim();
35
+ const contentSize = request.headers['content-length'];
36
+ const buffer = await stream2buffer(request, +contentSize || 0);
37
+ if (contentSize && buffer.length !== +contentSize)
38
+ throw new Error('Content-Length Incorrect');
39
+ const bodyString = buffer.toString();
40
+ if ('application/json' === contentType) {
41
+ return JSON.parse(bodyString);
42
+ }
43
+ else {
44
+ return bodyString;
45
+ }
46
+ }
47
+ exports.parseHTTPBody = parseHTTPBody;
48
+ /**
49
+ * http request
50
+ */
51
+ function httpRequest(url, options, body) {
52
+ return new Promise(function (resolve, reject) {
53
+ const request = http.request(url, options, async function (response) {
54
+ try {
55
+ const result = await parseHTTPBody(response);
56
+ resolve(result);
57
+ }
58
+ catch (error) {
59
+ const decoration = new Error(`${response.statusCode} - ${error.message}`);
60
+ reject(decoration);
61
+ }
62
+ });
63
+ request.on('error', reject);
64
+ if (body) {
65
+ request.method = 'POST';
66
+ request.setHeader('Content-Type', 'application/json');
67
+ request.setHeader('Content-Length', Buffer.byteLength(body));
68
+ request.write(body);
69
+ }
70
+ request.end();
71
+ });
72
+ }
73
+ exports.httpRequest = httpRequest;