Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: /upload endpoint for image uploads #74

Merged
merged 3 commits into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion .env.local.template
Original file line number Diff line number Diff line change
@@ -1,8 +1,27 @@
# There are a few backdoors that open themselves when NODE_ENV is set to
# 'development'. This would be the place to do that.
# NODE_ENV=development
NODE_ENV=development

# Required.
# Self explanatory. Used by bunfig.toml during install to gain acccess to
# Tendrel's private npm registry. Ask Fede if you don't have one.
NPM_TOKEN=

# Optional.
# So long as you aren't doing anything with S3/attachment uploads.
ATTACHMENT_BUCKET=

# Required.
# Used by Clerk's nextjs integration. Should be for the development instance.
CLERK_PUBLISHABLE_KEY=

# Required.
# Self explanatory. Get one from dashboard.clerk.com > api keys > add new key;
# name it after yourself. Use the development instance!
CLERK_SECRET_KEY=

# Required.
# One of the `TendrelStage`s as defined by the (rest) backend.
STAGE=dev

# vim: ft=sh
12 changes: 7 additions & 5 deletions bin/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import auth from "@/auth";
import { orm } from "@/datasources/postgres";
import i18n from "@/i18n";
import { type Context, resolvers, typeDefs } from "@/schema";
import upload from "@/upload";
import { ApolloServer } from "@apollo/server";
import { expressMiddleware } from "@apollo/server/express4";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
Expand Down Expand Up @@ -36,22 +37,23 @@ app.use(
morgan(
":date[iso] :method :url :status :res[content-length] - :response-time ms",
),
cors({
// for w3c trace context propagation
allowedHeaders: "*",
}),
);

app.use((req, _, next) => {
if (process.env.DEBUG_HEADERS) {
console.log(JSON.stringify(req.headers, null, 2));
}

next();
});

app.post("/upload", auth.clerk(), express.json(), upload.POST);

app.use(
"/",
cors({
// for w3c trace context propagation
allowedHeaders: "*",
}),
auth.clerk(),
i18n.accept(),
express.json(),
Expand Down
Binary file modified bun.lockb
Binary file not shown.
3 changes: 3 additions & 0 deletions copilot/graphql/manifest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ environments:
DB_NAME:
secretsmanager: "/database/service/graphql:dbname::"
variables:
ATTACHMENT_BUCKET: test-lambdastack-photostoragebucketcc7aea4f-1cnysolqfj44u
LOG_LEVEL: debug
beta:
nlb:
Expand All @@ -85,3 +86,5 @@ environments:
secretsmanager: "/database/service/graphql:port::"
DB_NAME:
secretsmanager: "/database/service/graphql:dbname::"
variables:
ATTACHMENT_BUCKET: beta-lambdastack-photostoragebucketcc7aea4f-1ang3xq3j0cqv
5 changes: 2 additions & 3 deletions lib/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { decodeGlobalId } from "@/schema/system";
import {
ClerkExpressWithAuth,
ClerkExpressRequireAuth,
type StrictAuthProp,
} from "@clerk/clerk-sdk-node";
import type e from "express";
Expand All @@ -24,7 +24,6 @@ export default {
//
// tl;dr if you set the 'x-tendrel-user' header to a Clerk user id, we will
// use that as the authenticated identity
const clerkMiddleware = ClerkExpressWithAuth();
return async (req: e.Request, res: e.Response, next: e.NextFunction) => {
if (process.env.NODE_ENV === "development") {
const userId = req.headers["x-tendrel-user"];
Expand All @@ -38,7 +37,7 @@ export default {
}
}

clerkMiddleware(req, res, next);
ClerkExpressRequireAuth()(req, res, next);
};
},
};
Expand Down
33 changes: 33 additions & 0 deletions lib/upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { randomUUID } from "node:crypto";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import type express from "express";
import z from "myzod";

const parser = z.object({
filename: z.string(),
mimetype: z.string(),
size: z.number(),
});

const s3 = new S3Client();

const POST: express.RequestHandler = async (
req: express.Request,
res: express.Response,
) => {
const { filename, mimetype, size } = parser.parse(req.body);
console.log(
`Requesting presigned upload url for ${filename} (${mimetype} ${size}B)`,
);

const Bucket = process.env.ATTACHMENT_BUCKET as string;
const Key = `${randomUUID()}/${filename}`;
const command = new PutObjectCommand({ Bucket, Key });
console.log(`Presigning upload url for s3://${Bucket}/${Key}`);

const url = await getSignedUrl(s3, command);
res.json({ uri: `s3://${Bucket}/${Key}`, url: url });
};

export default { POST };
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@
},
"dependencies": {
"@apollo/server": "^4.10.4",
"@aws-sdk/client-s3": "^3.685.0",
"@aws-sdk/s3-request-presigner": "^3.685.0",
"@aws-sdk/client-s3": "^3.692.0",
"@aws-sdk/s3-request-presigner": "^3.692.0",
"@clerk/clerk-sdk-node": "^5.0.12",
"@clerk/shared": "^2.3.1",
"@formatjs/intl-localematcher": "^0.5.4",
Expand Down