Skip to content

Commit

Permalink
Fix file stream (#5592)
Browse files Browse the repository at this point in the history
* much cleaner stream management

* change pipeline promise name, remove comments

* changeset

* Update .changeset/quick-shirts-cry.md
  • Loading branch information
gwyneplaine committed May 3, 2021
1 parent 3f5ee97 commit 1043243
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
5 changes: 5 additions & 0 deletions .changeset/quick-shirts-cry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystone-next/keystone': patch
---

Fixed uncaught exception in file stream.
25 changes: 9 additions & 16 deletions packages-next/keystone/src/lib/context/createFilesContext.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'path';
import crypto from 'crypto';
import { pipeline } from 'stream';
import filenamify from 'filenamify';
import { FilesConfig, FilesContext } from '@keystone-next/types';
import fs from 'fs-extra';
Expand Down Expand Up @@ -65,26 +66,18 @@ export function createFilesContext(config?: FilesConfig): FilesContext | undefin
const { upload: mode } = config;
const safeFilename = generateSafeFilename(filename, config.transformFilename);
const writeStream = fs.createWriteStream(path.join(storagePath, safeFilename));
const observeStreamErrors: Promise<void> = new Promise((resolve, reject) => {
writeStream.on('close', () => {
resolve();
});
// reject on both writeStream and read stream errors
writeStream.on('error', err => {
reject(err);
});
stream.on('error', err => {
reject(err);
const pipeStreams: Promise<void> = new Promise((resolve, reject) => {
pipeline(stream, writeStream, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});

for await (let chunk of stream) {
writeStream.write(chunk);
}
writeStream.close();

try {
await observeStreamErrors;
await pipeStreams;
const { size: filesize } = await fs.stat(path.join(storagePath, safeFilename));
return { mode, filesize, filename: safeFilename };
} catch (e) {
Expand Down

1 comment on commit 1043243

@vercel
Copy link

@vercel vercel bot commented on 1043243 May 3, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.