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

Add Route for Next App Directory #156

Merged
merged 6 commits into from
Oct 27, 2023
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
47 changes: 47 additions & 0 deletions packages/next-s3-upload/src/app/api/s3-upload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { NextResponse, NextRequest } from 'next/server';
import { S3Config } from '../../utils/config';
import { sanitizeKey, uuid } from '../../utils/keys';
import { route } from '../../utils/route-builder';

type NextAppRouteHandler = (req: NextRequest) => Promise<Response>;

type Configure = (options: Options) => Handler;
type Handler = NextAppRouteHandler & { configure: Configure };

type Options = S3Config & {
key?: (req: NextRequest, filename: string) => string | Promise<string>;
};

const makeRouteHandler = (options: Options = {}): Handler => {
const nextAppRoute: NextAppRouteHandler = async function(req) {
const reqBody = await req.json();
const { filename } = reqBody;

const { key, ...s3Options } = options;

const fileKey = key
? await Promise.resolve(key(req, filename))
: `next-s3-uploads/${uuid()}/${sanitizeKey(filename)}`;

try {
const response = await route({
body: reqBody,
s3Options: s3Options,
fileKey: fileKey,
});

return NextResponse.json(response);
} catch (e) {
console.error(e);
return NextResponse.error();
}
};

const configure = (options: Options) => makeRouteHandler(options);

return Object.assign(nextAppRoute, { configure });
};

const AppAPIRoute = makeRouteHandler();

export { AppAPIRoute };
122 changes: 24 additions & 98 deletions packages/next-s3-upload/src/pages/api/s3-upload.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
import { NextApiRequest, NextApiResponse } from 'next';
import {
STSClient,
GetFederationTokenCommand,
STSClientConfig,
} from '@aws-sdk/client-sts';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { getConfig, S3Config } from '../../utils/config';
import { getClient } from '../../utils/client';
import { S3Config } from '../../utils/config';
import { sanitizeKey, uuid } from '../../utils/keys';
import { route } from '../../utils/route-builder';

type NextRouteHandler = (
req: NextApiRequest,
Expand All @@ -23,100 +16,33 @@ type Options = S3Config & {
};

let makeRouteHandler = (options: Options = {}): Handler => {
let route: NextRouteHandler = async function(req, res) {
let config = getConfig({
accessKeyId: options.accessKeyId,
secretAccessKey: options.secretAccessKey,
bucket: options.bucket,
region: options.region,
forcePathStyle: options.forcePathStyle,
endpoint: options.endpoint,
});

let missing = missingEnvs(config);
if (missing.length > 0) {
res
.status(500)
.json({ error: `Next S3 Upload: Missing ENVs ${missing.join(', ')}` });
} else {
let uploadType = req.body._nextS3?.strategy;
let filename = req.body.filename;

let key = options.key
? await Promise.resolve(options.key(req, filename))
: `next-s3-uploads/${uuid()}/${sanitizeKey(filename)}`;
let { bucket, region, endpoint } = config;

if (uploadType === 'presigned') {
let filetype = req.body.filetype;
let client = getClient(config);
let params = {
Bucket: bucket,
Key: key,
ContentType: filetype,
CacheControl: 'max-age=630720000',
};

const url = await getSignedUrl(client, new PutObjectCommand(params), {
expiresIn: 60 * 60,
});

res.status(200).json({
key,
bucket,
region,
endpoint,
url,
});
} else {
let stsConfig: STSClientConfig = {
credentials: {
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
},
region,
};

let policy = {
Statement: [
{
Sid: 'Stmt1S3UploadAssets',
Effect: 'Allow',
Action: ['s3:PutObject'],
Resource: [`arn:aws:s3:::${bucket}/${key}`],
},
],
};

let sts = new STSClient(stsConfig);

let command = new GetFederationTokenCommand({
Name: 'S3UploadWebToken',
Policy: JSON.stringify(policy),
DurationSeconds: 60 * 60, // 1 hour
});

let token = await sts.send(command);

res.status(200).json({
token,
key,
bucket,
region,
});
}
const nextPageRoute: NextRouteHandler = async function(req, res) {
const { body: reqBody } = req.body;
const { filename } = reqBody;

const { key, ...s3Options } = options;

const fileKey = key
? await Promise.resolve(key(req, filename))
: `next-s3-uploads/${uuid()}/${sanitizeKey(filename)}`;

try {
const body = await route({
body: reqBody,
s3Options: s3Options,
fileKey: fileKey,
});

res.status(200).json(body);
} catch (e) {
console.error(e);
res.status(500).json({ error: 'Internal Server Error' });
}
};

let configure = (options: Options) => makeRouteHandler(options);

return Object.assign(route, { configure });
};

let missingEnvs = (config: Record<string, any>): string[] => {
let required = ['accessKeyId', 'secretAccessKey', 'bucket', 'region'];

return required.filter(key => !config[key] || config.key === '');
return Object.assign(nextPageRoute, { configure });
};

let APIRoute = makeRouteHandler();
Expand Down
132 changes: 132 additions & 0 deletions packages/next-s3-upload/src/utils/route-builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import {
STSClient,
GetFederationTokenCommand,
STSClientConfig,
GetFederationTokenCommandOutput,
} from '@aws-sdk/client-sts';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { getConfig, S3Config } from './config';
import { getClient } from './client';

export class RouteBuilderError extends Error {
constructor(message: string) {
super(message);
this.name = 'RouteBuilderError';
}
}

type RouteRequest = {
_nextS3?: {
strategy: any;
};
filename: string;
filetype: string;
};

type BaseRouteHandler = ({
body,
fileKey,
s3Options,
}: {
body: RouteRequest;
fileKey: string;
s3Options: S3Config;
}) => Promise<
| {
fileKey: string;
bucket: string;
region: string;
endpoint?: string;
url: string;
}
| {
token: GetFederationTokenCommandOutput;
fileKey: string;
bucket: string;
region: string;
}
>;

export const route: BaseRouteHandler = async function({
body,
fileKey,
s3Options,
}) {
const config = getConfig(s3Options);

const missing = missingEnvs(config);
if (missing.length > 0) {
throw new RouteBuilderError(
`Next S3 Upload: Missing ENVs ${missing.join(', ')}`
);
}

const uploadType = body._nextS3?.strategy;
const { bucket, region, endpoint } = config;

if (uploadType === 'presigned') {
const { filetype } = body;
const client = getClient(config);
const params = {
Bucket: bucket,
Key: fileKey,
ContentType: filetype,
CacheControl: 'max-age=630720000',
};

const url = await getSignedUrl(client, new PutObjectCommand(params), {
expiresIn: 60 * 60,
});

return {
fileKey,
bucket,
region,
endpoint,
url,
};
} else {
const stsConfig: STSClientConfig = {
credentials: {
accessKeyId: config.accessKeyId,
secretAccessKey: config.secretAccessKey,
},
region,
};

const policy = {
Statement: [
{
Sid: 'Stmt1S3UploadAssets',
Effect: 'Allow',
Action: ['s3:PutObject'],
Resource: [`arn:aws:s3:::${bucket}/${fileKey}`],
},
],
};

const sts = new STSClient(stsConfig);

const command = new GetFederationTokenCommand({
Name: 'S3UploadWebToken',
Policy: JSON.stringify(policy),
DurationSeconds: 60 * 60, // 1 hour
});

const token = await sts.send(command);

return {
token,
fileKey,
bucket,
region,
};
}
};

const missingEnvs = (config: Record<string, any>): string[] => {
const required = ['accessKeyId', 'secretAccessKey', 'bucket', 'region'];

return required.filter(key => !config[key] || config.key === '');
};