Skip to content

Commit

Permalink
fix: when getting data from post await until isLast is set to true (#58)
Browse files Browse the repository at this point in the history
* fix: when getting data from post await until isLast is set to true

Documentation: https://unetworking.github.io/uWebSockets.js/generated/interfaces/HttpResponse.html\#onData.onData-1
Example: https://github.com/uNetworking/uWebSockets.js/blob/master/examples/JsonPost.js

* fix: TS errors, add missing catch and refactor

* fix: prevent write on socket after connection end

---------

Co-authored-by: puria <[email protected]>
  • Loading branch information
matteo-cristino and puria authored Feb 28, 2024
1 parent c59e439 commit 0549669
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import {
openapiTemplate
} from './openapi.js';
import { SlangroomManager } from './slangroom.js';
import { getSchema, handleArrayBuffer, validateData } from './utils.js';
import { getSchema, validateData } from './utils.js';
dotenv.config();

const L = config.logger;
Expand Down Expand Up @@ -282,7 +282,10 @@ const generateRoutes = (app: TemplatedApp) => {
} catch (e) {
LOG.fatal(e);
res.cork(() =>
res.writeStatus('500').writeHeader('Content-Type', 'application/json').end(e.message)
res
.writeStatus('500')
.writeHeader('Content-Type', 'application/json')
.end((e as Error).message)
);
return;
}
Expand All @@ -306,21 +309,31 @@ const generateRoutes = (app: TemplatedApp) => {
res.writeStatus('500').writeHeader('Content-Type', 'application/json').end('Aborted');
});

try {
res.onData(async (d) => {
let buffer: Buffer;
res.onData((d, isLast) => {
let chunk = Buffer.from(d);
if (isLast) {
let data;
try {
const data = handleArrayBuffer(d);
execZencodeAndReply(res, req, data);
data = JSON.parse(buffer ? Buffer.concat([buffer, chunk]) : chunk);
} catch (e) {
LOG.fatal(e);
res.writeStatus('500').writeHeader('Content-Type', 'application/json').end(e.message);
L.error(e);
res
.writeStatus('500')
.writeHeader('Content-Type', 'application/json')
.end((e as Error).message);
return;
}
});
} catch (e) {
LOG.fatal(e);
res.writeStatus('500').writeHeader('Content-Type', 'application/json').end(e.message);
}
execZencodeAndReply(res, req, data);
return;
} else {
if (buffer) {
buffer = Buffer.concat([buffer, chunk]);
} else {
buffer = Buffer.concat([chunk]);
}
}
});
});

app.get(path, async (res, req) => {
Expand Down

0 comments on commit 0549669

Please sign in to comment.