@alizadefaig/pos-server 1.2.3 → 1.2.5-dev.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.
Files changed (3) hide show
  1. package/app/proxy.js +126 -120
  2. package/package.json +2 -2
  3. package/server.js +1 -3
package/app/proxy.js CHANGED
@@ -24,142 +24,148 @@ const loadProxy = (app) => {
24
24
  let appConfig = getConfig();
25
25
  let PROXY_TARGET = appConfig.apiUrl;
26
26
  const logger = getLogger();
27
- app.use(async (req, res, next) => {
28
- try {
29
- const targetUrl = PROXY_TARGET + req.originalUrl;
30
- const config = {
31
- method: req.method,
32
- url: targetUrl,
33
- headers: {...req.headers, host: new URL(PROXY_TARGET).host},
34
- };
35
-
36
- if (req.body && Object.keys(req.body).length > 0) {
37
- config.data = req.body;
38
- }
27
+ const proxyMode = appConfig.proxyMode || 'axios';
28
+ const changeOrigin = appConfig.changeProxyOrigin || false;
29
+ if (proxyMode === 'axios') {
30
+ app.use(async (req, res, next) => {
31
+ try {
32
+ const targetUrl = PROXY_TARGET + req.originalUrl;
33
+ const config = {
34
+ method: req.method,
35
+ url: targetUrl,
36
+ headers: {...req.headers, host: new URL(PROXY_TARGET).host},
37
+ };
38
+
39
+ if (req.body && Object.keys(req.body).length > 0) {
40
+ config.data = req.body;
41
+ }
39
42
 
40
- if (req.files && req.files.length > 0) {
41
- const FormData = require('form-data');
42
- const form = new FormData();
43
- req.files.forEach(file => {
44
- form.append(file.fieldname, file.buffer, file.originalname);
45
- });
43
+ if (req.files && req.files.length > 0) {
44
+ const FormData = require('form-data');
45
+ const form = new FormData();
46
+ req.files.forEach(file => {
47
+ form.append(file.fieldname, file.buffer, file.originalname);
48
+ });
46
49
 
47
- Object.entries(req.body).forEach(([key, value]) => {
48
- form.append(key, value);
49
- });
50
+ Object.entries(req.body).forEach(([key, value]) => {
51
+ form.append(key, value);
52
+ });
50
53
 
51
- config.data = form;
52
- config.headers = {...config.headers, ...form.getHeaders(), 'Accept': 'application/json'};
53
- }
54
+ config.data = form;
55
+ config.headers = {...config.headers, ...form.getHeaders(), 'Accept': 'application/json'};
56
+ }
54
57
 
55
- const response = await axios(config);
58
+ const response = await axios(config);
56
59
 
57
60
 
58
- res.status(response.status);
59
- // Object.entries(response.headers).forEach(([key, value]) => {
60
- // res.setHeader(key, value);
61
- // });
61
+ res.status(response.status);
62
+ // Object.entries(response.headers).forEach(([key, value]) => {
63
+ // res.setHeader(key, value);
64
+ // });
62
65
 
63
- const responseData = response.data;
66
+ const responseData = response.data;
64
67
 
65
68
 
66
- if (typeof responseData === 'string' || Buffer.isBuffer(responseData)) {
67
- res.send(responseData);
68
- } else {
69
- res.json(responseData);
70
- }
69
+ if (typeof responseData === 'string' || Buffer.isBuffer(responseData)) {
70
+ res.send(responseData);
71
+ } else {
72
+ res.json(responseData);
73
+ }
71
74
 
72
- } catch (error) {
73
- if (error.response) {
74
- // Если сервер вернул ответ с ошибкой
75
- res.status(error.response.status);
75
+ } catch (error) {
76
+ if (error.response) {
77
+ // Если сервер вернул ответ с ошибкой
78
+ res.status(error.response.status);
76
79
 
77
80
 
78
- if (error.response.data && typeof error.response.data === 'object') {
79
- const details = await streamToString(error.response.data)
80
- res.json({error: 'Ошибка от проксируемого сервера', details});
81
+ if (error.response.data && typeof error.response.data === 'object') {
82
+ const details = await streamToString(error.response.data)
83
+ res.json({error: 'Ошибка от проксируемого сервера', details});
84
+ } else {
85
+ res.send(error.response.data);
86
+ }
81
87
  } else {
82
- res.send(error.response.data);
88
+ // Внутренняя ошибка сервера (например, таймаут или потеря связи)
89
+ res.status(500).json({error: 'Внутренняя ошибка прокси', details: error.message});
83
90
  }
84
- } else {
85
- // Внутренняя ошибка сервера (например, таймаут или потеря связи)
86
- res.status(500).json({error: 'Внутренняя ошибка прокси', details: error.message});
87
- }
88
91
 
89
92
 
90
- console.error('Ошибка при проксировании запроса:', error.message);
91
- }
92
- });
93
- // const proxy = createProxyMiddleware({
94
- // target: PROXY_TARGET,
95
- // changeOrigin: true,
96
- // on: {
97
- // proxyReq: (proxyReq, req, res, options) => {
98
- // const traceId = uuidv4();
99
- // const timeStamp = moment.utc().unix();
100
- // proxyReq.setHeader('trace-id', traceId);
101
- // req.traceId = traceId;
102
- // logger.log({
103
- // traceId,
104
- // timeStamp,
105
- // request: {
106
- // headers: req.headers,
107
- // method: req.method,
108
- // url: req.url,
109
- // body: req.data,
110
- // params: req.params,
111
- // }
112
- // })
113
- // return fixRequestBody(proxyReq, req);
114
- // },
115
- // proxyRes: (proxyRes, req, res, options) => {
116
- // const traceId = req.traceId;
117
- // const timeStamp = moment.utc().unix();
118
- // // proxyRes.setHeader('Content-Type', 'application/json');
119
- //
120
- //
121
- // let body = Buffer.from('');
122
- //
123
- // proxyRes.on('data', (chunk) => {
124
- // body = Buffer.concat([body, chunk]);
125
- // });
126
- //
127
- // proxyRes.on('end', () => {
128
- // const responseBody = body.toString('utf8');
129
- //
130
- // let response = responseBody;
131
- // try {
132
- // response = JSON.parse(responseBody);
133
- // } catch (e) {
134
- // response = responseBody;
135
- // }
136
- //
137
- // logger.log({
138
- // traceId,
139
- // timeStamp,
140
- // response
141
- // })
142
- // });
143
- // },
144
- // error: (err, req, res, target) => {
145
- // const traceId = req.traceId;
146
- // const timeStamp = moment.utc().unix();
147
- // logger.error({
148
- // traceId,
149
- // timeStamp,
150
- // error: err
151
- // })
152
- //
153
- // res.end(JSON.stringify({
154
- // error: 'Bad Gateway',
155
- // message: err.message,
156
- // traceId: req.traceId || null,
157
- // }));
158
- // }
159
- // },
160
- // selfHandleResponse: false
161
- // });
162
- // app.use(proxy);
93
+ console.error('Ошибка при проксировании запроса:', error.message);
94
+ }
95
+ });
96
+ } else {
97
+ console.log('HTTP-PROXY')
98
+ const proxy = createProxyMiddleware({
99
+ target: PROXY_TARGET,
100
+ changeOrigin,
101
+ on: {
102
+ proxyReq: (proxyReq, req, res, options) => {
103
+ const traceId = uuidv4();
104
+ const timeStamp = moment.utc().unix();
105
+ proxyReq.setHeader('trace-id', traceId);
106
+ req.traceId = traceId;
107
+ logger.log({
108
+ traceId,
109
+ timeStamp,
110
+ request: {
111
+ headers: req.headers,
112
+ method: req.method,
113
+ url: req.url,
114
+ body: req.data,
115
+ params: req.params,
116
+ }
117
+ })
118
+ return fixRequestBody(proxyReq, req);
119
+ },
120
+ proxyRes: (proxyRes, req, res, options) => {
121
+ const traceId = req.traceId;
122
+ const timeStamp = moment.utc().unix();
123
+ // proxyRes.setHeader('Content-Type', 'application/json');
124
+
125
+
126
+ let body = Buffer.from('');
127
+
128
+ proxyRes.on('data', (chunk) => {
129
+ body = Buffer.concat([body, chunk]);
130
+ });
131
+
132
+ proxyRes.on('end', () => {
133
+ const responseBody = body.toString('utf8');
134
+
135
+ let response = responseBody;
136
+ try {
137
+ response = JSON.parse(responseBody);
138
+ } catch (e) {
139
+ response = responseBody;
140
+ }
141
+
142
+ logger.log({
143
+ traceId,
144
+ timeStamp,
145
+ response
146
+ })
147
+ });
148
+ },
149
+ error: (err, req, res, target) => {
150
+ const traceId = req.traceId;
151
+ const timeStamp = moment.utc().unix();
152
+ logger.error({
153
+ traceId,
154
+ timeStamp,
155
+ error: err
156
+ })
157
+
158
+ res.end(JSON.stringify({
159
+ error: 'Bad Gateway',
160
+ message: err.message,
161
+ traceId: req.traceId || null,
162
+ }));
163
+ }
164
+ },
165
+ selfHandleResponse: false
166
+ });
167
+ app.use(proxy);
168
+ }
163
169
  }
164
170
  module.exports = {
165
171
  loadProxy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alizadefaig/pos-server",
3
- "version": "1.2.3",
3
+ "version": "1.2.5-dev.1",
4
4
  "description": "Server in express js with Proxy to Main server if need and will work with Electron JS",
5
5
  "homepage": "https://gitlab.com/faigalizade/pos-server#readme",
6
6
  "bugs": {
@@ -12,7 +12,7 @@
12
12
  },
13
13
  "dependencies": {
14
14
  "@alizadefaig/cafetap-escpos-usb": "^1.0.1",
15
- "axios": "^1.8.4",
15
+ "axios": "^1.9.0",
16
16
  "cors": "^2.8.5",
17
17
  "escpos": "^3.0.0-alpha.6",
18
18
  "escpos-network": "^3.0.0-alpha.5",
package/server.js CHANGED
@@ -17,9 +17,7 @@ const upload = multer();
17
17
  app.use(express.json({limit: '500mb'}));
18
18
  app.use(express.urlencoded({extended: true, limit: '500mb'}));
19
19
  app.use(upload.any());
20
- app.use(cors({
21
- origin: "*",
22
- }));
20
+ app.use(cors());
23
21
 
24
22
 
25
23