From 28a39bccf96549a35ef77c10dce5f90f9f8cc654 Mon Sep 17 00:00:00 2001 From: otofune Date: Mon, 6 Nov 2017 15:39:16 +0900 Subject: [PATCH] file-server - support new DriveFile w/ GridFS on '/:id/:name' --- src/file/server.ts | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/src/file/server.ts b/src/file/server.ts index 068e88546..f38599b89 100644 --- a/src/file/server.ts +++ b/src/file/server.ts @@ -128,17 +128,28 @@ app.get('/:id/:name', async (req, res) => { return; } - const file = await File.findOne({ _id: new mongodb.ObjectID(req.params.id) }); + const fileId = new mongodb.ObjectID(req.params.id) + const file = await DriveFile.findOne({ _id: fileId }); if (file == null) { res.status(404).sendFile(`${__dirname}/assets/dummy.png`); return; - } else if (file.data == null) { - res.sendStatus(400); - return; } - send(file.data.buffer, file.type, req, res); + const bucket = await getGridFSBucket() + + const buffer = await ((id): Promise => new Promise((resolve, reject) => { + const chunks = [] + const readableStream = bucket.openDownloadStream(id) + readableStream.on('data', chunk => { + chunks.push(chunk); + }) + readableStream.on('end', () => { + resolve(Buffer.concat(chunks)) + }) + }))(fileId) + + send(buffer, file.metadata.type, req, res); }); module.exports = app;