-
-
Notifications
You must be signed in to change notification settings - Fork 558
/
getUploadURL.ts
46 lines (40 loc) 路 1.26 KB
/
getUploadURL.ts
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { GraphQLFieldConfig, GraphQLNonNull, GraphQLString } from "graphql";
import { customAlphabet } from "nanoid/async";
import path from "path";
import { Context } from "../context";
import { storage } from "../core";
import env from "../env";
const newId = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz", 12);
/**
* Generates a URL for user uploaded content that expires in 10 minutes.
*
* @example
* mutation {
* getUploadURL(fileName: "photo.jpg")
* }
*/
export const getUploadURL: GraphQLFieldConfig<unknown, Context> = {
type: GraphQLString,
args: {
fileName: { type: new GraphQLNonNull(GraphQLString) },
contentType: { type: GraphQLString },
},
async resolve(self, args, ctx) {
// Only authenticated users can upload files
ctx.ensureAuthorized();
// Create a temporary for the uploaded content
const fileName = `${await newId()}${path.extname(args.fileName)}`;
const [url] = await storage
.bucket(env.UPLOAD_BUCKET)
.file(fileName)
.getSignedUrl({
action: "write",
version: "v4",
expires: Date.now() + 600000 /* 10 min */,
contentType: args.contentType,
virtualHostedStyle: true,
cname: `https://${env.UPLOAD_BUCKET}`,
});
return url;
},
};