@alizadefaig/pos-server 1.2.2 → 1.2.4

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 +131 -65
  2. package/package.json +1 -1
  3. package/server.js +1 -3
package/app/proxy.js CHANGED
@@ -24,76 +24,142 @@ const loadProxy = (app) => {
24
24
  let appConfig = getConfig();
25
25
  let PROXY_TARGET = appConfig.apiUrl;
26
26
  const logger = getLogger();
27
- const proxy = createProxyMiddleware({
28
- target: PROXY_TARGET,
29
- changeOrigin: true,
30
- on: {
31
- proxyReq: (proxyReq, req, res, options) => {
32
- const traceId = uuidv4();
33
- const timeStamp = moment.utc().unix();
34
- proxyReq.setHeader('trace-id', traceId);
35
- req.traceId = traceId;
36
- logger.log({
37
- traceId,
38
- timeStamp,
39
- request: {
40
- headers: req.headers,
41
- method: req.method,
42
- url: req.url,
43
- body: req.data,
44
- params: req.params,
45
- }
46
- })
47
- return fixRequestBody(proxyReq, req);
48
- },
49
- proxyRes: (proxyRes, req, res, options) => {
50
- const traceId = req.traceId;
51
- const timeStamp = moment.utc().unix();
52
- // proxyRes.setHeader('Content-Type', 'application/json');
53
-
54
-
55
- let body = Buffer.from('');
56
-
57
- proxyRes.on('data', (chunk) => {
58
- body = Buffer.concat([body, chunk]);
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
+ }
39
+
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);
59
45
  });
60
46
 
61
- proxyRes.on('end', () => {
62
- const responseBody = body.toString('utf8');
63
-
64
- let response = responseBody;
65
- try {
66
- response = JSON.parse(responseBody);
67
- } catch (e) {
68
- response = responseBody;
69
- }
70
-
71
- logger.log({
72
- traceId,
73
- timeStamp,
74
- response
75
- })
47
+ Object.entries(req.body).forEach(([key, value]) => {
48
+ form.append(key, value);
76
49
  });
77
- },
78
- error: (err, req, res, target) => {
79
- const traceId = req.traceId;
80
- const timeStamp = moment.utc().unix();
81
- logger.error({
82
- traceId,
83
- timeStamp,
84
- error: err
85
- })
86
-
87
- res.end(JSON.stringify({
88
- error: 'Bad Gateway',
89
- message: err.message,
90
- traceId: req.traceId || null,
91
- }));
50
+
51
+ config.data = form;
52
+ config.headers = {...config.headers, ...form.getHeaders(), 'Accept': 'application/json'};
92
53
  }
93
- },
94
- selfHandleResponse: false
54
+
55
+ const response = await axios(config);
56
+
57
+
58
+ res.status(response.status);
59
+ // Object.entries(response.headers).forEach(([key, value]) => {
60
+ // res.setHeader(key, value);
61
+ // });
62
+
63
+ const responseData = response.data;
64
+
65
+
66
+ if (typeof responseData === 'string' || Buffer.isBuffer(responseData)) {
67
+ res.send(responseData);
68
+ } else {
69
+ res.json(responseData);
70
+ }
71
+
72
+ } catch (error) {
73
+ if (error.response) {
74
+ // Если сервер вернул ответ с ошибкой
75
+ res.status(error.response.status);
76
+
77
+
78
+ if (error.response.data && typeof error.response.data === 'object') {
79
+ const details = await streamToString(error.response.data)
80
+ res.json({error: 'Ошибка от проксируемого сервера', details});
81
+ } else {
82
+ res.send(error.response.data);
83
+ }
84
+ } else {
85
+ // Внутренняя ошибка сервера (например, таймаут или потеря связи)
86
+ res.status(500).json({error: 'Внутренняя ошибка прокси', details: error.message});
87
+ }
88
+
89
+
90
+ console.error('Ошибка при проксировании запроса:', error.message);
91
+ }
95
92
  });
96
- app.use(proxy);
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);
97
163
  }
98
164
  module.exports = {
99
165
  loadProxy
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alizadefaig/pos-server",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
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": {
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