Skip to content

Commit

Permalink
feat: start middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
pedromtec committed Oct 16, 2024
1 parent a99b6bc commit d3c0cb6
Show file tree
Hide file tree
Showing 4 changed files with 1,001 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"sideEffects": false,
"dependencies": {
"@antfu/ni": "^0.21.12",
"@aws-sdk/client-dynamodb": "^3.670.0",
"@builder.io/partytown": "^0.6.1",
"@envelop/core": "^5.0.2",
"@envelop/graphql-jit": "^8.0.3",
Expand Down
35 changes: 35 additions & 0 deletions packages/core/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { RedirectsClient } from 'src/sdk/redirects'

const redirectsClient = new RedirectsClient()

export async function middleware(req: NextRequest) {
const { pathname } = req.nextUrl

const redirect = await redirectsClient.get(pathname)

if (redirect) {
console.log('redirect matched', redirect)
const url = req.nextUrl.clone()
url.pathname = redirect.to

const redirectStatusCode = redirect.type === 'permanent' ? 308 : 307
return NextResponse.redirect(url, redirectStatusCode)
}

return NextResponse.next()
}

export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|_next/image|favicon.ico).*)',
],
}
49 changes: 49 additions & 0 deletions packages/core/src/sdk/redirects/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/* eslint-disable turbo/no-undeclared-env-vars */
import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb'
import storeConfig from '../../../discovery.config'

const dynamoDbClient = new DynamoDBClient({
region: 'us-east-1',
credentials: {
accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
sessionToken: process.env.AWS_SESSION_TOKEN,
},
})

const TABLE_NAME = 'faststore-redirects'
const ACCOUNT_ID = storeConfig.api.storeId

export class RedirectsClient {
async get(from: string) {
try {
const command = new GetItemCommand({
TableName: TABLE_NAME,
Key: {
account_name: {
S: ACCOUNT_ID,
},
from: {
S: from,
},
},
})

const { Item } = await dynamoDbClient.send(command)

if (!Item) {
return
}

const redirect = {
to: Item.to.S,
from: Item.from.S,
type: Item.type.S,
}

return redirect
} catch (error) {
console.error(error)
}
}
}
Loading

0 comments on commit d3c0cb6

Please sign in to comment.