summaryrefslogtreecommitdiff
path: root/src/server/file/send-drive-file.ts
blob: e6ee19ff1d985b96b45323a03451f9a25c04331e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import * as Koa from 'koa';
import * as send from 'koa-send';
import * as mongodb from 'mongodb';
import DriveFile, { getGridFSBucket } from '../../models/drive-file';
import pour from './pour';

export default async function(ctx: Koa.Context) {
	// Validate id
	if (!mongodb.ObjectID.isValid(ctx.params.id)) {
		ctx.throw(400, 'incorrect id');
		return;
	}

	const fileId = new mongodb.ObjectID(ctx.params.id);

	// Fetch drive file
	const file = await DriveFile.findOne({ _id: fileId });

	if (file == null) {
		ctx.status = 404;
		await send(ctx, `${__dirname}/assets/dummy.png`);
		return;
	}

	const bucket = await getGridFSBucket();

	const readable = bucket.openDownloadStream(fileId);

	pour(readable, file.contentType, ctx);
}