node-pluginsmanager-plugin 5.1.1 → 6.0.1

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,28 +1,31 @@
1
- import { iServerResponse } from "./Server";
2
- import DescriptorUser, { iDescriptorUserOptions } from "./DescriptorUser";
3
- import { OpenApiValidator } from "express-openapi-validate";
4
- export interface iUrlParameters {
5
- "path": {
6
- [key: string]: any;
7
- };
8
- "query": {
9
- [key: string]: any;
10
- };
11
- "headers": {
12
- [key: string]: any;
13
- };
14
- "cookies": {
15
- [key: string]: any;
16
- };
17
- }
18
- export interface iBodyParameters {
19
- [key: string]: any;
20
- }
21
- export default class Mediator extends DescriptorUser {
22
- protected _validator: OpenApiValidator | null;
23
- constructor(options: iDescriptorUserOptions);
24
- checkParameters(operationId: string, urlParams: iUrlParameters, bodyParams: iBodyParameters): Promise<void>;
25
- checkResponse(operationId: string, res: iServerResponse): Promise<void>;
26
- init(...data: any): Promise<void>;
27
- release(...data: any): Promise<void>;
28
- }
1
+ import { iIncomingMessage, iServerResponse } from "./Server";
2
+ import DescriptorUser, { iDescriptorUserOptions } from "./DescriptorUser";
3
+ import { OpenApiValidator } from "express-openapi-validate";
4
+ export interface iIncomingMessageForMediatorValidation extends iIncomingMessage {
5
+ "body": any;
6
+ }
7
+ export interface iServerResponseForMediatorValidation extends iServerResponse {
8
+ "body": any;
9
+ }
10
+ export interface iUrlParameters {
11
+ "path": {
12
+ [key: string]: any;
13
+ };
14
+ "query": {
15
+ [key: string]: any;
16
+ };
17
+ "headers": {
18
+ [key: string]: any;
19
+ };
20
+ "cookies": {
21
+ [key: string]: any;
22
+ };
23
+ }
24
+ export default class Mediator extends DescriptorUser {
25
+ protected _validator: OpenApiValidator | null;
26
+ constructor(options: iDescriptorUserOptions);
27
+ checkParameters(operationId: string, urlParams: iUrlParameters, bodyParams: string): Promise<void>;
28
+ checkResponse(operationId: string, res: iServerResponseForMediatorValidation): Promise<void>;
29
+ init(...data: any): Promise<void>;
30
+ release(...data: any): Promise<void>;
31
+ }
@@ -1,145 +1,151 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const checkObject_1 = require("../checkers/TypeError/checkObject");
7
- const checkNonEmptyString_1 = require("../checkers/RangeError/checkNonEmptyString");
8
- const checkNonEmptyObject_1 = require("../checkers/RangeError/checkNonEmptyObject");
9
- const extractPathMethodByOperationId_1 = __importDefault(require("../utils/descriptor/extractPathMethodByOperationId"));
10
- const DescriptorUser_1 = __importDefault(require("./DescriptorUser"));
11
- // types & interfaces
12
- // externals
13
- const express_openapi_validate_1 = require("express-openapi-validate");
14
- // module
15
- class Mediator extends DescriptorUser_1.default {
16
- // constructor
17
- constructor(options) {
18
- super(options);
19
- this._validator = null;
20
- }
21
- // public
22
- // Check sended parameters by method name (used by the Server)
23
- checkParameters(operationId, urlParams, bodyParams) {
24
- // parameters validation
25
- return this.checkDescriptor().then(() => {
26
- return (0, checkNonEmptyString_1.checkNonEmptyString)("operationId", operationId);
27
- }).then(() => {
28
- return (0, checkNonEmptyObject_1.checkNonEmptyObject)("urlParams", urlParams).then(() => {
29
- return (0, checkObject_1.checkObject)("urlParams.path", urlParams.path);
30
- }).then(() => {
31
- return (0, checkObject_1.checkObject)("urlParams.query", urlParams.query);
32
- }).then(() => {
33
- return (0, checkObject_1.checkObject)("urlParams.headers", urlParams.headers);
34
- }).then(() => {
35
- return (0, checkObject_1.checkObject)("urlParams.cookies", urlParams.cookies);
36
- });
37
- }).then(() => {
38
- return (0, checkObject_1.checkObject)("bodyParams", bodyParams);
39
- }).then(() => {
40
- // search wanted operation
41
- const foundPathMethod = (0, extractPathMethodByOperationId_1.default)(this._Descriptor.paths, operationId);
42
- return !foundPathMethod ? Promise.reject(new ReferenceError("Unknown operationId \"" + operationId + "\"")) : new Promise((resolve, reject) => {
43
- const req = {
44
- "path": foundPathMethod.path,
45
- "method": foundPathMethod.method,
46
- "params": urlParams.path,
47
- "query": urlParams.query,
48
- "headers": urlParams.headers,
49
- "cookies": urlParams.cookies,
50
- "body": bodyParams
51
- };
52
- const validateRequest = this._validator.validate(req.method, req.path); // set to "any" for ts validation
53
- validateRequest(req, null, (err) => {
54
- return err ? reject(err) : resolve();
55
- });
56
- });
57
- }).catch((err) => {
58
- return err instanceof express_openapi_validate_1.ValidationError ? Promise.resolve().then(() => {
59
- switch (err.data[0].keyword) { // extract first Error
60
- case "required":
61
- return Promise.reject(new ReferenceError(err.message));
62
- case "type":
63
- return Promise.reject(new TypeError(err.message));
64
- case "minimum":
65
- case "maximum":
66
- case "minLength":
67
- case "maxLength":
68
- case "minItems":
69
- case "maxItems":
70
- case "enum":
71
- return Promise.reject(new RangeError(err.message));
72
- default:
73
- return Promise.reject(new Error(err.message));
74
- }
75
- }) : Promise.reject(err);
76
- });
77
- }
78
- // Check sended parameters by method name (used by the Server)
79
- checkResponse(operationId, res) {
80
- // parameters validation
81
- return this.checkDescriptor().then(() => {
82
- return (0, checkNonEmptyString_1.checkNonEmptyString)("operationId", operationId);
83
- }).then(() => {
84
- // search wanted operation
85
- const foundPathMethod = (0, extractPathMethodByOperationId_1.default)(this._Descriptor.paths, operationId);
86
- return !foundPathMethod ? Promise.reject(new ReferenceError("Unknown operationId \"" + operationId + "\"")) : new Promise((resolve, reject) => {
87
- // no content, no validation
88
- if (204 === res.statusCode) {
89
- return "undefined" !== typeof res.body ? reject(new ReferenceError("You should not have content data with 204 statusCode")) : resolve();
90
- }
91
- // no content, no validation (put requests)
92
- else if (201 === res.statusCode && "undefined" === typeof res.body) {
93
- return resolve();
94
- }
95
- // validator cannot correctly check pure boolean return
96
- else if ("undefined" !== typeof res.body && ["true", "false"].includes(res.body)) {
97
- return resolve();
98
- }
99
- else {
100
- try {
101
- res.headers = res.getHeaders();
102
- if ("undefined" === typeof res.body) {
103
- res.body = null;
104
- }
105
- else {
106
- res.body = "string" === typeof res.body ? JSON.parse(res.body) : res.body;
107
- }
108
- const validateResponse = this._validator.validateResponse(foundPathMethod.method, foundPathMethod.path);
109
- validateResponse(res);
110
- return resolve();
111
- }
112
- catch (e) {
113
- return reject(new Error("[" + foundPathMethod.method + "]" +
114
- foundPathMethod.path +
115
- " (" + foundPathMethod.operationId + ") => " +
116
- res.statusCode +
117
- "\r\n" +
118
- (e.message ? e.message : e)));
119
- }
120
- }
121
- });
122
- });
123
- }
124
- // init / release
125
- init(...data) {
126
- return this._initWorkSpace(...data).then(() => {
127
- this._validator = new express_openapi_validate_1.OpenApiValidator(this._Descriptor);
128
- this.initialized = true;
129
- this.emit("initialized", ...data);
130
- });
131
- }
132
- release(...data) {
133
- return this._releaseWorkSpace(...data).then(() => {
134
- // can only be released by Orchestrator
135
- this._Descriptor = null;
136
- this._validator = null;
137
- this.initialized = false;
138
- this.emit("released", ...data);
139
- }).then(() => {
140
- this.removeAllListeners();
141
- });
142
- }
143
- }
144
- exports.default = Mediator;
145
- ;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const checkExists_1 = require("../checkers/ReferenceError/checkExists");
7
+ const checkObject_1 = require("../checkers/TypeError/checkObject");
8
+ const checkNonEmptyString_1 = require("../checkers/RangeError/checkNonEmptyString");
9
+ const checkNonEmptyObject_1 = require("../checkers/RangeError/checkNonEmptyObject");
10
+ const extractPathMethodByOperationId_1 = __importDefault(require("../utils/descriptor/extractPathMethodByOperationId"));
11
+ const jsonParser_1 = __importDefault(require("../utils/jsonParser"));
12
+ const DescriptorUser_1 = __importDefault(require("./DescriptorUser"));
13
+ // types & interfaces
14
+ // externals
15
+ const express_openapi_validate_1 = require("express-openapi-validate");
16
+ ;
17
+ ;
18
+ ;
19
+ // module
20
+ class Mediator extends DescriptorUser_1.default {
21
+ // constructor
22
+ constructor(options) {
23
+ super(options);
24
+ this._validator = null;
25
+ }
26
+ // public
27
+ // Check sended parameters by method name (used by the Server)
28
+ checkParameters(operationId, urlParams, bodyParams) {
29
+ // parameters validation
30
+ return this.checkDescriptor().then(() => {
31
+ return (0, checkNonEmptyString_1.checkNonEmptyString)("operationId", operationId);
32
+ }).then(() => {
33
+ return (0, checkNonEmptyObject_1.checkNonEmptyObject)("urlParams", urlParams).then(() => {
34
+ return (0, checkObject_1.checkObject)("urlParams.path", urlParams.path);
35
+ }).then(() => {
36
+ return (0, checkObject_1.checkObject)("urlParams.query", urlParams.query);
37
+ }).then(() => {
38
+ return (0, checkObject_1.checkObject)("urlParams.headers", urlParams.headers);
39
+ }).then(() => {
40
+ return (0, checkObject_1.checkObject)("urlParams.cookies", urlParams.cookies);
41
+ });
42
+ }).then(() => {
43
+ return (0, checkExists_1.checkExists)("bodyParams", bodyParams);
44
+ }).then(() => {
45
+ // search wanted operation
46
+ const foundPathMethod = (0, extractPathMethodByOperationId_1.default)(this._Descriptor.paths, operationId);
47
+ return !foundPathMethod ? Promise.reject(new ReferenceError("Unknown operationId \"" + operationId + "\"")) : new Promise((resolve, reject) => {
48
+ const req = {
49
+ "path": foundPathMethod.path,
50
+ "method": foundPathMethod.method,
51
+ "params": urlParams.path,
52
+ "query": urlParams.query,
53
+ "headers": urlParams.headers,
54
+ "cookies": urlParams.cookies,
55
+ "body": bodyParams
56
+ };
57
+ const validateRequest = this._validator.validate(req.method, req.path); // set to "any" for ts validation
58
+ validateRequest(req, null, (err) => {
59
+ return err ? reject(err) : resolve();
60
+ });
61
+ });
62
+ }).catch((err) => {
63
+ return err instanceof express_openapi_validate_1.ValidationError ? Promise.resolve().then(() => {
64
+ switch (err.data[0].keyword) { // extract first Error
65
+ case "required":
66
+ return Promise.reject(new ReferenceError(err.message));
67
+ case "type":
68
+ return Promise.reject(new TypeError(err.message));
69
+ case "minimum":
70
+ case "maximum":
71
+ case "minLength":
72
+ case "maxLength":
73
+ case "minItems":
74
+ case "maxItems":
75
+ case "enum":
76
+ return Promise.reject(new RangeError(err.message));
77
+ default:
78
+ return Promise.reject(new Error(err.message));
79
+ }
80
+ }) : Promise.reject(err);
81
+ });
82
+ }
83
+ // Check sended parameters by method name (used by the Server)
84
+ checkResponse(operationId, res) {
85
+ // parameters validation
86
+ return this.checkDescriptor().then(() => {
87
+ return (0, checkNonEmptyString_1.checkNonEmptyString)("operationId", operationId);
88
+ }).then(() => {
89
+ // search wanted operation
90
+ const foundPathMethod = (0, extractPathMethodByOperationId_1.default)(this._Descriptor.paths, operationId);
91
+ return !foundPathMethod ? Promise.reject(new ReferenceError("Unknown operationId \"" + operationId + "\"")) : new Promise((resolve, reject) => {
92
+ // no content, no validation
93
+ if (204 === res.statusCode) {
94
+ return "undefined" !== typeof res.body ? reject(new ReferenceError("You should not have content data with 204 statusCode")) : resolve();
95
+ }
96
+ // no content, no validation (put requests)
97
+ else if (201 === res.statusCode && "undefined" === typeof res.body) {
98
+ return resolve();
99
+ }
100
+ // validator cannot correctly check pure boolean return
101
+ else if ("undefined" !== typeof res.body && ["true", "false"].includes(res.body)) {
102
+ return resolve();
103
+ }
104
+ else {
105
+ try {
106
+ const mutedRes = Object.assign({}, res);
107
+ mutedRes.headers = res.getHeaders();
108
+ if ("undefined" === typeof mutedRes.body || "" === mutedRes.body) {
109
+ mutedRes.body = {};
110
+ }
111
+ else {
112
+ mutedRes.body = (0, jsonParser_1.default)(mutedRes.body);
113
+ }
114
+ const validateResponse = this._validator.validateResponse(foundPathMethod.method, foundPathMethod.path);
115
+ validateResponse(mutedRes);
116
+ return resolve();
117
+ }
118
+ catch (e) {
119
+ return reject(new Error("[" + foundPathMethod.method + "]" +
120
+ foundPathMethod.path +
121
+ " (" + foundPathMethod.operationId + ") => " +
122
+ res.statusCode +
123
+ "\r\n" +
124
+ (e.message ? e.message : e)));
125
+ }
126
+ }
127
+ });
128
+ });
129
+ }
130
+ // init / release
131
+ init(...data) {
132
+ return this._initWorkSpace(...data).then(() => {
133
+ this._validator = new express_openapi_validate_1.OpenApiValidator(this._Descriptor);
134
+ this.initialized = true;
135
+ this.emit("initialized", ...data);
136
+ });
137
+ }
138
+ release(...data) {
139
+ return this._releaseWorkSpace(...data).then(() => {
140
+ // can only be released by Orchestrator
141
+ this._Descriptor = null;
142
+ this._validator = null;
143
+ this.initialized = false;
144
+ this.emit("released", ...data);
145
+ }).then(() => {
146
+ this.removeAllListeners();
147
+ });
148
+ }
149
+ }
150
+ exports.default = Mediator;
151
+ ;
@@ -1,55 +1,55 @@
1
- /// <reference types="node" />
2
- import MediatorUser from "./MediatorUser";
3
- import { IncomingMessage, ServerResponse } from "node:http";
4
- import { Server as WebSocketServer } from "ws";
5
- import { Server as SocketIOServer } from "socket.io";
6
- import { iMediatorUserOptions } from "./MediatorUser";
7
- export interface iClient {
8
- "id": string;
9
- "status": "CONNECTED" | "DISCONNECTED";
10
- }
11
- export interface iIncomingMessage extends IncomingMessage {
12
- "method": string;
13
- "pattern": string;
14
- "validatedIp": string;
15
- "headers": {
16
- [key: string]: any;
17
- };
18
- "cookies": {
19
- [key: string]: any;
20
- };
21
- "query": {
22
- [key: string]: any;
23
- };
24
- "params": {
25
- [key: string]: any;
26
- };
27
- "body": any;
28
- }
29
- export interface iServerResponse extends ServerResponse {
30
- "body": any;
31
- "headers": {
32
- [key: string]: any;
33
- };
34
- }
35
- export default class Server extends MediatorUser {
36
- protected _socketServer: WebSocketServer | SocketIOServer | null;
37
- protected _checkParameters: boolean;
38
- protected _checkResponse: boolean;
39
- protected _cors: boolean;
40
- constructor(opt: iMediatorUserOptions);
41
- protected _serverType(): "NO_SERVER" | "WEBSOCKET" | "SOCKETIO" | "UNKNOWN";
42
- disableCheckParameters(): this;
43
- enableCheckParameters(): this;
44
- disableCheckResponse(): this;
45
- enableCheckResponse(): this;
46
- disableCors(): this;
47
- enableCors(): this;
48
- appMiddleware(req: iIncomingMessage, res: iServerResponse, next: Function): void;
49
- socketMiddleware(socketServer: WebSocketServer | SocketIOServer): void;
50
- push(command: string, data?: any, log?: boolean): this;
51
- getClients(): Array<iClient>;
52
- pushClient(clientId: string, command: string, data: any, log?: boolean): this;
53
- init(...data: any): Promise<void>;
54
- release(...data: any): Promise<void>;
55
- }
1
+ /// <reference types="node" />
2
+ import MediatorUser from "./MediatorUser";
3
+ import { IncomingMessage, ServerResponse } from "node:http";
4
+ import { Server as WebSocketServer } from "ws";
5
+ import { Server as SocketIOServer } from "socket.io";
6
+ import { iMediatorUserOptions } from "./MediatorUser";
7
+ export interface iClient {
8
+ "id": string;
9
+ "status": "CONNECTED" | "DISCONNECTED";
10
+ }
11
+ export interface iIncomingMessage extends IncomingMessage {
12
+ "method": string;
13
+ "pattern": string;
14
+ "validatedIp": string;
15
+ "headers": {
16
+ [key: string]: any;
17
+ };
18
+ "cookies": {
19
+ [key: string]: any;
20
+ };
21
+ "query": {
22
+ [key: string]: any;
23
+ };
24
+ "params": {
25
+ [key: string]: any;
26
+ };
27
+ "body": string;
28
+ }
29
+ export interface iServerResponse extends ServerResponse {
30
+ "body": string;
31
+ "headers": {
32
+ [key: string]: any;
33
+ };
34
+ }
35
+ export default class Server extends MediatorUser {
36
+ protected _socketServer: WebSocketServer | SocketIOServer | null;
37
+ protected _checkParameters: boolean;
38
+ protected _checkResponse: boolean;
39
+ protected _cors: boolean;
40
+ constructor(opt: iMediatorUserOptions);
41
+ protected _serverType(): "NO_SERVER" | "WEBSOCKET" | "SOCKETIO" | "UNKNOWN";
42
+ disableCheckParameters(): this;
43
+ enableCheckParameters(): this;
44
+ disableCheckResponse(): this;
45
+ enableCheckResponse(): this;
46
+ disableCors(): this;
47
+ enableCors(): this;
48
+ appMiddleware(req: iIncomingMessage, res: iServerResponse, next: Function): void;
49
+ socketMiddleware(socketServer: WebSocketServer | SocketIOServer): void;
50
+ push(command: string, data?: any, log?: boolean): this;
51
+ getClients(): Array<iClient>;
52
+ pushClient(clientId: string, command: string, data: any, log?: boolean): this;
53
+ init(...data: any): Promise<void>;
54
+ release(...data: any): Promise<void>;
55
+ }
@@ -19,6 +19,8 @@ const extractSchemaType_1 = __importDefault(require("../utils/descriptor/extract
19
19
  const extractBody_1 = __importDefault(require("../utils/request/extractBody"));
20
20
  const extractIp_1 = __importDefault(require("../utils/request/extractIp"));
21
21
  const extractCookies_1 = __importDefault(require("../utils/request/extractCookies"));
22
+ const extractMime_1 = __importDefault(require("../utils/request/extractMime"));
23
+ const jsonParser_1 = __importDefault(require("../utils/jsonParser"));
22
24
  const send_1 = __importDefault(require("../utils/send"));
23
25
  const cleanSendedError_1 = __importDefault(require("../utils/cleanSendedError"));
24
26
  const MediatorUser_1 = __importDefault(require("./MediatorUser"));
@@ -106,37 +108,46 @@ class Server extends MediatorUser_1.default {
106
108
  else if ("string" === typeof req.headers["content-length"]) {
107
109
  req.headers["content-length"] = parseInt(req.headers["content-length"], 10);
108
110
  }
109
- // set default content-type
110
- if ("string" !== typeof req.headers["content-type"]) {
111
- req.headers["content-type"] = "application/json";
112
- }
113
111
  if (!req.pattern || !this._Descriptor.paths[req.pattern] || !this._Descriptor.paths[req.pattern][req.method]) {
114
112
  return next();
115
113
  }
116
114
  const { operationId } = this._Descriptor.paths[req.pattern][req.method];
115
+ const apiVersion = this._Descriptor.info.version;
116
+ const contentType = req.headers["content-type"] || req.headers["Content-Type"] || "";
117
+ const responses = this._Descriptor.paths[req.pattern][req.method].responses;
117
118
  this._log("info", "" +
118
119
  "=> [" + req.validatedIp + "] " + req.url + " (" + req.method.toUpperCase() + ")" +
119
120
  (operationId ? node_os_1.EOL + "operationId : " + operationId : "") +
120
- node_os_1.EOL + "content-type : " + req.headers["content-type"] +
121
+ (req.headers["content-type"] ? node_os_1.EOL + "content-type : " + req.headers["content-type"] : "") +
121
122
  ("get" !== req.method && req.headers["content-length"] && 4 < req.headers["content-length"] ?
122
123
  node_os_1.EOL + "content-length : " + req.headers["content-length"] : ""));
123
124
  // get descriptor
124
125
  if ("/" + this._Descriptor.info.title + "/api/descriptor" === req.pattern && "get" === req.method) {
125
126
  // add current server
126
127
  const port = res.socket && res.socket.localPort ? res.socket.localPort : ((_a = res.socket) === null || _a === void 0 ? void 0 : _a.address()).port;
127
- this._Descriptor.servers.push({
128
+ const descriptor = Object.assign({}, this._Descriptor);
129
+ descriptor.servers.push({
128
130
  "url": req.validatedIp + ":" + port,
129
131
  "description": "Actual current server"
130
132
  });
131
- this._log("info", "<= [" + req.validatedIp + "] " + JSON.stringify(this._Descriptor));
132
- return (0, send_1.default)(req, res, serverCodes_1.default.OK, this._Descriptor, this._Descriptor.info.version, this._cors).catch((err) => {
133
+ const content = JSON.stringify(descriptor);
134
+ this._log("info", "<= [" + req.validatedIp + "] " + content);
135
+ return (0, send_1.default)(req, res, serverCodes_1.default.OK, content, {
136
+ "apiVersion": apiVersion,
137
+ "cors": this._cors,
138
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.OK, responses)
139
+ }).catch((err) => {
133
140
  this._log("error", err);
134
- const result = {
141
+ const result = JSON.stringify({
135
142
  "code": "INTERNAL_SERVER_ERROR",
136
143
  "message": (0, cleanSendedError_1.default)(err)
137
- };
138
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
139
- return (0, send_1.default)(req, res, serverCodes_1.default.INTERNAL_SERVER_ERROR, result, this._Descriptor.info.version, this._cors);
144
+ });
145
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
146
+ return (0, send_1.default)(req, res, serverCodes_1.default.INTERNAL_SERVER_ERROR, result, {
147
+ "apiVersion": apiVersion,
148
+ "cors": this._cors,
149
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.INTERNAL_SERVER_ERROR, responses)
150
+ });
140
151
  });
141
152
  }
142
153
  // get plugin status
@@ -144,34 +155,50 @@ class Server extends MediatorUser_1.default {
144
155
  const initialized = this.initialized && this._Mediator.initialized;
145
156
  const status = initialized ? "INITIALIZED" : "ENABLED";
146
157
  this._log("info", "<= [" + req.validatedIp + "] " + status);
147
- return (0, send_1.default)(req, res, serverCodes_1.default.OK, status, this._Descriptor.info.version, this._cors);
158
+ return (0, send_1.default)(req, res, serverCodes_1.default.OK, JSON.stringify(status), {
159
+ "apiVersion": apiVersion,
160
+ "cors": this._cors,
161
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.OK, responses)
162
+ });
148
163
  }
149
164
  // missing operationId
150
165
  else if (!operationId) {
151
- const result = {
166
+ const result = JSON.stringify({
152
167
  "code": "NOT_IMPLEMENTED",
153
168
  "message": "Missing \"operationId\" in the Descriptor for this request"
154
- };
155
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
156
- return (0, send_1.default)(req, res, serverCodes_1.default.NOT_IMPLEMENTED, result, this._Descriptor.info.version, this._cors);
169
+ });
170
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
171
+ return (0, send_1.default)(req, res, serverCodes_1.default.NOT_IMPLEMENTED, result, {
172
+ "apiVersion": apiVersion,
173
+ "cors": this._cors,
174
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.NOT_IMPLEMENTED, responses)
175
+ });
157
176
  }
158
177
  // not implemented operationId
159
178
  else if ("function" !== typeof this._Mediator[operationId]) {
160
- const result = {
179
+ const result = JSON.stringify({
161
180
  "code": "NOT_IMPLEMENTED",
162
181
  "message": "Unknown Mediator's \"operationId\" method for this request"
163
- };
164
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
165
- return (0, send_1.default)(req, res, serverCodes_1.default.NOT_IMPLEMENTED, result, this._Descriptor.info.version, this._cors);
182
+ });
183
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
184
+ return (0, send_1.default)(req, res, serverCodes_1.default.NOT_IMPLEMENTED, result, {
185
+ "apiVersion": apiVersion,
186
+ "cors": this._cors,
187
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.NOT_IMPLEMENTED, responses)
188
+ });
166
189
  }
167
190
  // no "Content-Length" header found
168
191
  else if ("get" !== req.method && null !== (0, checkInteger_1.checkIntegerSync)("headers[\"content-length\"]", req.headers["content-length"])) {
169
- const result = {
192
+ const result = JSON.stringify({
170
193
  "code": "MISSING_HEADER",
171
194
  "message": "No valid \"Content-Length\" header found"
172
- };
173
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
174
- return (0, send_1.default)(req, res, serverCodes_1.default.MISSING_HEADER, result, this._Descriptor.info.version, this._cors);
195
+ });
196
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
197
+ return (0, send_1.default)(req, res, serverCodes_1.default.MISSING_HEADER, result, {
198
+ "apiVersion": apiVersion,
199
+ "cors": this._cors,
200
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.MISSING_HEADER, responses)
201
+ });
175
202
  }
176
203
  else {
177
204
  // force formate for path parameters
@@ -244,16 +271,19 @@ class Server extends MediatorUser_1.default {
244
271
  // extract body
245
272
  }).then(() => {
246
273
  if ("get" === req.method.toLowerCase()) {
247
- return Promise.resolve({});
274
+ return Promise.resolve("");
248
275
  }
249
- else if (!(0, checkNonEmptyObject_1.checkNonEmptyObjectSync)("body", req.body)) {
276
+ else if (!(0, checkNonEmptyString_1.checkNonEmptyStringSync)("body", req.body)) {
250
277
  return Promise.resolve(req.body);
251
278
  }
252
279
  else {
253
280
  return (0, extractBody_1.default)(req).then((body) => {
254
- req.body = body.parsed;
255
- if (body.value.length) {
256
- this._log("log", body.value);
281
+ if (body.length) {
282
+ this._log("log", body);
283
+ req.body = (0, jsonParser_1.default)(body);
284
+ }
285
+ else {
286
+ req.body = "";
257
287
  }
258
288
  return Promise.resolve(req.body);
259
289
  });
@@ -282,71 +312,111 @@ class Server extends MediatorUser_1.default {
282
312
  if ("put" === req.method) {
283
313
  if ("undefined" === typeof content || null === content) {
284
314
  this._log("success", "<= [" + req.validatedIp + "] no content");
285
- return (0, send_1.default)(req, res, serverCodes_1.default.OK_PUT, undefined, this._Descriptor.info.version, this._cors);
315
+ return (0, send_1.default)(req, res, serverCodes_1.default.OK_PUT, "", {
316
+ "apiVersion": apiVersion,
317
+ "cors": this._cors,
318
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.OK_PUT, responses)
319
+ });
286
320
  }
287
321
  else {
288
- this._log("success", "<= [" + req.validatedIp + "] " + JSON.stringify(content));
289
- return (0, send_1.default)(req, res, serverCodes_1.default.OK_PUT, content, this._Descriptor.info.version, this._cors);
322
+ this._log("success", "<= [" + req.validatedIp + "] " + content);
323
+ return (0, send_1.default)(req, res, serverCodes_1.default.OK_PUT, content, {
324
+ "apiVersion": apiVersion,
325
+ "cors": this._cors,
326
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.OK_PUT, responses)
327
+ });
290
328
  }
291
329
  }
292
330
  // no content
293
331
  else if ("undefined" === typeof content || null === content) {
294
332
  this._log("warning", "<= [" + req.validatedIp + "] no content");
295
- return (0, send_1.default)(req, res, serverCodes_1.default.OK_NO_CONTENT, undefined, this._Descriptor.info.version, this._cors);
333
+ return (0, send_1.default)(req, res, serverCodes_1.default.OK_NO_CONTENT, "", {
334
+ "apiVersion": apiVersion,
335
+ "cors": this._cors,
336
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.OK_NO_CONTENT, responses)
337
+ });
296
338
  }
297
339
  else {
298
- this._log("success", "<= [" + req.validatedIp + "] " + JSON.stringify(content));
299
- return (0, send_1.default)(req, res, serverCodes_1.default.OK, content, this._Descriptor.info.version, this._cors);
340
+ this._log("success", "<= [" + req.validatedIp + "] " + content);
341
+ return (0, send_1.default)(req, res, serverCodes_1.default.OK, content, {
342
+ "apiVersion": apiVersion,
343
+ "cors": this._cors,
344
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.OK, responses)
345
+ });
300
346
  }
301
347
  }).catch((err) => {
302
348
  if (err instanceof ReferenceError) {
303
- const result = {
349
+ const result = JSON.stringify({
304
350
  "code": "MISSING_PARAMETER",
305
351
  "message": (0, cleanSendedError_1.default)(err)
306
- };
307
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
308
- return (0, send_1.default)(req, res, serverCodes_1.default.MISSING_PARAMETER, result, this._Descriptor.info.version, this._cors);
352
+ });
353
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
354
+ return (0, send_1.default)(req, res, serverCodes_1.default.MISSING_PARAMETER, result, {
355
+ "apiVersion": apiVersion,
356
+ "cors": this._cors,
357
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.MISSING_PARAMETER, responses)
358
+ });
309
359
  }
310
360
  else if (err instanceof TypeError) {
311
- const result = {
361
+ const result = JSON.stringify({
312
362
  "code": "WRONG_TYPE_PARAMETER",
313
363
  "message": (0, cleanSendedError_1.default)(err)
314
- };
315
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
316
- return (0, send_1.default)(req, res, serverCodes_1.default.WRONG_TYPE_PARAMETER, result, this._Descriptor.info.version, this._cors);
364
+ });
365
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
366
+ return (0, send_1.default)(req, res, serverCodes_1.default.WRONG_TYPE_PARAMETER, result, {
367
+ "apiVersion": apiVersion,
368
+ "cors": this._cors,
369
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.WRONG_TYPE_PARAMETER, responses)
370
+ });
317
371
  }
318
372
  else if (err instanceof RangeError) {
319
- const result = {
373
+ const result = JSON.stringify({
320
374
  "code": "EMPTY_OR_RANGE_OR_ENUM_PARAMETER",
321
375
  "message": (0, cleanSendedError_1.default)(err)
322
- };
323
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
324
- return (0, send_1.default)(req, res, serverCodes_1.default.EMPTY_OR_RANGE_OR_ENUM_PARAMETER, result, this._Descriptor.info.version, this._cors);
376
+ });
377
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
378
+ return (0, send_1.default)(req, res, serverCodes_1.default.EMPTY_OR_RANGE_OR_ENUM_PARAMETER, result, {
379
+ "apiVersion": apiVersion,
380
+ "cors": this._cors,
381
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.EMPTY_OR_RANGE_OR_ENUM_PARAMETER, responses)
382
+ });
325
383
  }
326
384
  else if (err instanceof SyntaxError) {
327
- const result = {
385
+ const result = JSON.stringify({
328
386
  "code": "JSON_PARSE",
329
387
  "message": (0, cleanSendedError_1.default)(err)
330
- };
331
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
332
- return (0, send_1.default)(req, res, serverCodes_1.default.JSON_PARSE, result, this._Descriptor.info.version, this._cors);
388
+ });
389
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
390
+ return (0, send_1.default)(req, res, serverCodes_1.default.JSON_PARSE, result, {
391
+ "apiVersion": apiVersion,
392
+ "cors": this._cors,
393
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.JSON_PARSE, responses)
394
+ });
333
395
  }
334
396
  else if (err instanceof NotFoundError_1.default) {
335
- const result = {
397
+ const result = JSON.stringify({
336
398
  "code": "NOT_FOUND",
337
399
  "message": (0, cleanSendedError_1.default)(err)
338
- };
339
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
340
- return (0, send_1.default)(req, res, serverCodes_1.default.NOT_FOUND, result, this._Descriptor.info.version, this._cors);
400
+ });
401
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
402
+ return (0, send_1.default)(req, res, serverCodes_1.default.NOT_FOUND, result, {
403
+ "apiVersion": apiVersion,
404
+ "cors": this._cors,
405
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.NOT_FOUND, responses)
406
+ });
341
407
  }
342
408
  else {
343
409
  this._log("error", err);
344
- const result = {
410
+ const result = JSON.stringify({
345
411
  "code": "INTERNAL_SERVER_ERROR",
346
412
  "message": (0, cleanSendedError_1.default)(err)
347
- };
348
- this._log("error", "<= [" + req.validatedIp + "] " + JSON.stringify(result));
349
- return (0, send_1.default)(req, res, serverCodes_1.default.INTERNAL_SERVER_ERROR, result, this._Descriptor.info.version, this._cors);
413
+ });
414
+ this._log("error", "<= [" + req.validatedIp + "] " + result);
415
+ return (0, send_1.default)(req, res, serverCodes_1.default.INTERNAL_SERVER_ERROR, result, {
416
+ "apiVersion": apiVersion,
417
+ "cors": this._cors,
418
+ "mime": (0, extractMime_1.default)(contentType, serverCodes_1.default.INTERNAL_SERVER_ERROR, responses)
419
+ });
350
420
  }
351
421
  // check response
352
422
  }).then(() => {
@@ -1,30 +1,30 @@
1
- import { checkExists, checkExistsSync } from "./checkers/ReferenceError/checkExists";
2
- import { checkBoolean, checkBooleanSync } from "./checkers/TypeError/checkBoolean";
3
- import { checkFunction, checkFunctionSync } from "./checkers/TypeError/checkFunction";
4
- import { checkNumber, checkNumberSync } from "./checkers/TypeError/checkNumber";
5
- import { checkObject, checkObjectSync } from "./checkers/TypeError/checkObject";
6
- import { checkString, checkStringSync } from "./checkers/TypeError/checkString";
7
- import { checkArray, checkArraySync } from "./checkers/TypeError/checkArray";
8
- import { checkInteger, checkIntegerSync } from "./checkers/TypeError/checkInteger";
9
- import { checkNonEmptyArray, checkNonEmptyArraySync } from "./checkers/RangeError/checkNonEmptyArray";
10
- import { checkNonEmptyInteger, checkNonEmptyIntegerSync } from "./checkers/RangeError/checkNonEmptyInteger";
11
- import { checkNonEmptyNumber, checkNonEmptyNumberSync } from "./checkers/RangeError/checkNonEmptyNumber";
12
- import { checkNonEmptyObject, checkNonEmptyObjectSync } from "./checkers/RangeError/checkNonEmptyObject";
13
- import { checkNonEmptyString, checkNonEmptyStringSync } from "./checkers/RangeError/checkNonEmptyString";
14
- import { checkNumberBetween, checkNumberBetweenSync } from "./checkers/RangeError/checkNumberBetween";
15
- import { checkObjectLength, checkObjectLengthSync } from "./checkers/RangeError/checkObjectLength";
16
- import { checkObjectLengthBetween, checkObjectLengthBetweenSync } from "./checkers/RangeError/checkObjectLengthBetween";
17
- import { checkStringLength, checkStringLengthSync } from "./checkers/RangeError/checkStringLength";
18
- import { checkStringLengthBetween, checkStringLengthBetweenSync } from "./checkers/RangeError/checkStringLengthBetween";
19
- import { checkIntegerBetween, checkIntegerBetweenSync } from "./checkers/RangeError/checkIntegerBetween";
20
- import { checkArrayLength, checkArrayLengthSync } from "./checkers/RangeError/checkArrayLength";
21
- import { checkArrayLengthBetween, checkArrayLengthBetweenSync } from "./checkers/RangeError/checkArrayLengthBetween";
22
- export { checkExists, checkExistsSync, checkBoolean, checkBooleanSync, checkFunction, checkFunctionSync, checkNumber, checkNumberSync, checkObject, checkObjectSync, checkString, checkStringSync, checkArray, checkArraySync, checkInteger, checkIntegerSync, checkNonEmptyArray, checkNonEmptyArraySync, checkNonEmptyInteger, checkNonEmptyIntegerSync, checkNonEmptyNumber, checkNonEmptyNumberSync, checkNonEmptyObject, checkNonEmptyObjectSync, checkNonEmptyString, checkNonEmptyStringSync, checkNumberBetween, checkNumberBetweenSync, checkObjectLength, checkObjectLengthSync, checkObjectLengthBetween, checkObjectLengthBetweenSync, checkStringLength, checkStringLengthSync, checkStringLengthBetween, checkStringLengthBetweenSync, checkIntegerBetween, checkIntegerBetweenSync, checkArrayLength, checkArrayLengthSync, checkArrayLengthBetween, checkArrayLengthBetweenSync };
23
- import DescriptorUser, { iDescriptorUserOptions, tLogType, tLogger } from "./components/DescriptorUser";
24
- import Mediator, { iUrlParameters, iBodyParameters } from "./components/Mediator";
25
- import MediatorUser, { iMediatorUserOptions } from "./components/MediatorUser";
26
- import NotFoundError from "./components/NotFoundError";
27
- import Orchestrator, { iOrchestratorOptions } from "./components/Orchestrator";
28
- import Server, { iClient, iIncomingMessage, iServerResponse } from "./components/Server";
29
- export { tLogType, tLogger, iUrlParameters, iBodyParameters, iClient, iIncomingMessage, iServerResponse };
30
- export { DescriptorUser, iDescriptorUserOptions, Mediator, MediatorUser, iMediatorUserOptions, NotFoundError, Orchestrator, iOrchestratorOptions, Server };
1
+ import { checkExists, checkExistsSync } from "./checkers/ReferenceError/checkExists";
2
+ import { checkBoolean, checkBooleanSync } from "./checkers/TypeError/checkBoolean";
3
+ import { checkFunction, checkFunctionSync } from "./checkers/TypeError/checkFunction";
4
+ import { checkNumber, checkNumberSync } from "./checkers/TypeError/checkNumber";
5
+ import { checkObject, checkObjectSync } from "./checkers/TypeError/checkObject";
6
+ import { checkString, checkStringSync } from "./checkers/TypeError/checkString";
7
+ import { checkArray, checkArraySync } from "./checkers/TypeError/checkArray";
8
+ import { checkInteger, checkIntegerSync } from "./checkers/TypeError/checkInteger";
9
+ import { checkNonEmptyArray, checkNonEmptyArraySync } from "./checkers/RangeError/checkNonEmptyArray";
10
+ import { checkNonEmptyInteger, checkNonEmptyIntegerSync } from "./checkers/RangeError/checkNonEmptyInteger";
11
+ import { checkNonEmptyNumber, checkNonEmptyNumberSync } from "./checkers/RangeError/checkNonEmptyNumber";
12
+ import { checkNonEmptyObject, checkNonEmptyObjectSync } from "./checkers/RangeError/checkNonEmptyObject";
13
+ import { checkNonEmptyString, checkNonEmptyStringSync } from "./checkers/RangeError/checkNonEmptyString";
14
+ import { checkNumberBetween, checkNumberBetweenSync } from "./checkers/RangeError/checkNumberBetween";
15
+ import { checkObjectLength, checkObjectLengthSync } from "./checkers/RangeError/checkObjectLength";
16
+ import { checkObjectLengthBetween, checkObjectLengthBetweenSync } from "./checkers/RangeError/checkObjectLengthBetween";
17
+ import { checkStringLength, checkStringLengthSync } from "./checkers/RangeError/checkStringLength";
18
+ import { checkStringLengthBetween, checkStringLengthBetweenSync } from "./checkers/RangeError/checkStringLengthBetween";
19
+ import { checkIntegerBetween, checkIntegerBetweenSync } from "./checkers/RangeError/checkIntegerBetween";
20
+ import { checkArrayLength, checkArrayLengthSync } from "./checkers/RangeError/checkArrayLength";
21
+ import { checkArrayLengthBetween, checkArrayLengthBetweenSync } from "./checkers/RangeError/checkArrayLengthBetween";
22
+ export { checkExists, checkExistsSync, checkBoolean, checkBooleanSync, checkFunction, checkFunctionSync, checkNumber, checkNumberSync, checkObject, checkObjectSync, checkString, checkStringSync, checkArray, checkArraySync, checkInteger, checkIntegerSync, checkNonEmptyArray, checkNonEmptyArraySync, checkNonEmptyInteger, checkNonEmptyIntegerSync, checkNonEmptyNumber, checkNonEmptyNumberSync, checkNonEmptyObject, checkNonEmptyObjectSync, checkNonEmptyString, checkNonEmptyStringSync, checkNumberBetween, checkNumberBetweenSync, checkObjectLength, checkObjectLengthSync, checkObjectLengthBetween, checkObjectLengthBetweenSync, checkStringLength, checkStringLengthSync, checkStringLengthBetween, checkStringLengthBetweenSync, checkIntegerBetween, checkIntegerBetweenSync, checkArrayLength, checkArrayLengthSync, checkArrayLengthBetween, checkArrayLengthBetweenSync };
23
+ import DescriptorUser, { iDescriptorUserOptions, tLogType, tLogger } from "./components/DescriptorUser";
24
+ import Mediator, { iUrlParameters } from "./components/Mediator";
25
+ import MediatorUser, { iMediatorUserOptions } from "./components/MediatorUser";
26
+ import NotFoundError from "./components/NotFoundError";
27
+ import Orchestrator, { iOrchestratorOptions } from "./components/Orchestrator";
28
+ import Server, { iClient, iIncomingMessage, iServerResponse } from "./components/Server";
29
+ export { tLogType, tLogger, iUrlParameters, iClient, iIncomingMessage, iServerResponse };
30
+ export { DescriptorUser, iDescriptorUserOptions, Mediator, MediatorUser, iMediatorUserOptions, NotFoundError, Orchestrator, iOrchestratorOptions, Server };
@@ -11,7 +11,7 @@ const checkFile_1 = __importDefault(require("./checkFile"));
11
11
  // module
12
12
  function readJSONFile(file) {
13
13
  return (0, checkFile_1.default)(file).then(() => {
14
- return (0, promises_1.readFile)(file, "utf8");
14
+ return (0, promises_1.readFile)(file, "utf-8");
15
15
  }).then((content) => {
16
16
  return Promise.resolve(JSON.parse(content));
17
17
  });
@@ -0,0 +1 @@
1
+ export default function jsonParser(content: string): any;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // module
4
+ function jsonParser(content) {
5
+ try {
6
+ let parsed = JSON.parse(content);
7
+ if ("string" === typeof parsed) {
8
+ parsed = jsonParser(parsed);
9
+ }
10
+ return parsed;
11
+ }
12
+ catch (e) {
13
+ return content;
14
+ }
15
+ }
16
+ exports.default = jsonParser;
17
+ ;
@@ -1,7 +1,2 @@
1
1
  import { iIncomingMessage } from "../../components/Server";
2
- interface iResult {
3
- "value": string;
4
- "parsed": any;
5
- }
6
- export default function extractBody(req: iIncomingMessage): Promise<iResult>;
7
- export {};
2
+ export default function extractBody(req: iIncomingMessage): Promise<string>;
@@ -17,13 +17,10 @@ function extractBody(req) {
17
17
  return new Promise((resolve, reject) => {
18
18
  let queryData = "";
19
19
  req.on("data", (data) => {
20
- queryData += data.toString("utf8");
20
+ queryData += data.toString("utf-8");
21
21
  }).on("end", () => {
22
22
  if ("" === queryData || "null" === queryData) {
23
- resolve({
24
- "value": "",
25
- "parsed": {}
26
- });
23
+ resolve("");
27
24
  }
28
25
  else {
29
26
  req.headers["content-length"] = parseInt(req.headers["content-length"], 10);
@@ -33,15 +30,7 @@ function extractBody(req) {
33
30
  " Do not forget the fact that it is a 8-bit bytes number."));
34
31
  }
35
32
  else {
36
- try {
37
- resolve({
38
- "value": queryData,
39
- "parsed": JSON.parse(queryData)
40
- });
41
- }
42
- catch (e) {
43
- reject(e);
44
- }
33
+ resolve(queryData);
45
34
  }
46
35
  }
47
36
  });
@@ -0,0 +1,8 @@
1
+ export default function extractMime(contentType: string, code: number, responses: {
2
+ [key: string]: {
3
+ "description": string;
4
+ "content"?: {
5
+ [key: string]: any;
6
+ };
7
+ };
8
+ }): string;
@@ -0,0 +1,68 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ // deps
4
+ // locals
5
+ const checkString_1 = require("../../checkers/TypeError/checkString");
6
+ const checkNonEmptyNumber_1 = require("../../checkers/RangeError/checkNonEmptyNumber");
7
+ const checkObject_1 = require("../../checkers/TypeError/checkObject");
8
+ // consts
9
+ const DEFAULT_MIME = "text/plain";
10
+ // module
11
+ function extractMime(contentType, code, responses) {
12
+ const err = (0, checkString_1.checkStringSync)("contentType", contentType) ||
13
+ (0, checkNonEmptyNumber_1.checkNonEmptyNumberSync)("code", code) ||
14
+ (0, checkObject_1.checkObjectSync)("responses", responses);
15
+ if (err) {
16
+ throw err;
17
+ }
18
+ else {
19
+ const stringifiedCode = String(code);
20
+ if (!responses[stringifiedCode] && !responses.default && "" !== contentType.trim()) {
21
+ return contentType;
22
+ }
23
+ else {
24
+ let descriptorContent;
25
+ if (responses[stringifiedCode]) {
26
+ if (responses[stringifiedCode].content) {
27
+ descriptorContent = responses[stringifiedCode].content;
28
+ }
29
+ }
30
+ else if (responses.default && responses.default.content) {
31
+ descriptorContent = responses.default.content;
32
+ }
33
+ else {
34
+ return DEFAULT_MIME;
35
+ }
36
+ const possibleMimes = descriptorContent ? Object.keys(descriptorContent) : [];
37
+ const [mimeRequest, charsetRequest] = contentType.split(";").map((content) => {
38
+ return content.trim().toLowerCase();
39
+ });
40
+ let result = DEFAULT_MIME; // default mime
41
+ if (!possibleMimes.length) {
42
+ if (mimeRequest) {
43
+ result = mimeRequest;
44
+ }
45
+ else {
46
+ result = DEFAULT_MIME;
47
+ }
48
+ }
49
+ else if (1 === possibleMimes.length) { // only one possible option
50
+ result = possibleMimes[0];
51
+ }
52
+ else {
53
+ if (mimeRequest && possibleMimes.includes(mimeRequest)) {
54
+ result = mimeRequest;
55
+ }
56
+ else {
57
+ result = DEFAULT_MIME;
58
+ }
59
+ }
60
+ if (charsetRequest) {
61
+ result = mimeRequest + "; " + charsetRequest;
62
+ }
63
+ return result;
64
+ }
65
+ }
66
+ }
67
+ exports.default = extractMime;
68
+ ;
@@ -1,2 +1,6 @@
1
1
  import { iIncomingMessage, iServerResponse } from "../components/Server";
2
- export default function send(req: iIncomingMessage, res: iServerResponse, code: number, content: any, apiVersion: string, cors: boolean): Promise<void>;
2
+ export default function send(req: iIncomingMessage, res: iServerResponse, code: number, content: string, options: {
3
+ "apiVersion": string;
4
+ "cors": boolean;
5
+ "mime": string;
6
+ }): Promise<void>;
@@ -1,20 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  // module
4
- function send(req, res, code, content, apiVersion, cors) {
4
+ function send(req, res, code, content, options) {
5
5
  return new Promise((resolve) => {
6
- // formate content
7
- if ("undefined" !== typeof content) {
8
- res.body = JSON.stringify(content);
9
- }
10
6
  // force data for checking
11
7
  res.statusCode = code;
12
8
  res.headers = Object.assign({
13
- "Content-Type": "application/json; charset=utf-8",
14
- "Content-Length": res.body ? Buffer.byteLength(res.body) : 0,
9
+ "Content-Type": options.mime,
10
+ "Content-Length": content ? Buffer.byteLength(content) : 0,
15
11
  "Status-Code-Url-Cat": "https://http.cat/" + code,
16
- "API-Version": apiVersion
17
- }, cors ? {
12
+ "API-Version": options.apiVersion
13
+ }, options.cors ? {
18
14
  "Access-Control-Allow-Origin": "*",
19
15
  "Access-Control-Allow-Credentials": true,
20
16
  "Access-Control-Allow-Methods": req.headers["access-control-request-method"] ? req.headers["access-control-request-method"] : [
@@ -41,8 +37,9 @@ function send(req, res, code, content, apiVersion, cors) {
41
37
  } : {});
42
38
  // send data
43
39
  res.writeHead(res.statusCode, res.headers);
44
- if (res.body) {
45
- res.end(res.body, "utf-8", () => {
40
+ if (content) {
41
+ res.body = content; // for Mediator response validator
42
+ res.end(content, "utf-8", () => {
46
43
  resolve();
47
44
  });
48
45
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
 
3
3
  "name": "node-pluginsmanager-plugin",
4
- "version": "5.1.1",
4
+ "version": "6.0.1",
5
5
  "description": "An abstract parent plugin for node-pluginsmanager",
6
6
 
7
7
  "type": "commonjs",
@@ -44,15 +44,15 @@
44
44
  "uniqid": "5.4.0"
45
45
  },
46
46
  "devDependencies": {
47
- "@types/express": "4.17.17",
48
- "@types/node": "20.5.9",
47
+ "@types/express": "4.17.21",
48
+ "@types/node": "20.10.1",
49
49
  "@types/socket.io": "3.0.2",
50
- "@types/uniqid": "5.3.2",
51
- "@types/ws": "8.5.5",
52
- "check-version-modules": "1.5.2",
50
+ "@types/uniqid": "5.3.4",
51
+ "@types/ws": "8.5.10",
52
+ "check-version-modules": "2.0.0",
53
53
  "coveralls": "3.1.1",
54
54
  "colors": "1.4.0",
55
- "eslint": "8.48.0",
55
+ "eslint": "8.54.0",
56
56
  "express": "4.18.2",
57
57
  "husky": "8.0.3",
58
58
  "mocha": "10.2.0",
@@ -60,9 +60,9 @@
60
60
  "openapi-types": "12.1.3",
61
61
  "socket.io": "4.7.2",
62
62
  "socket.io-client": "4.7.2",
63
- "typescript": "5.2.2",
63
+ "typescript": "5.3.2",
64
64
  "used-deps-analyzer": "0.1.8",
65
- "ws": "8.14.0"
65
+ "ws": "8.14.2"
66
66
  },
67
67
  "optionalDependencies": {},
68
68