Skip to content

Commit

Permalink
302 redirect
Browse files Browse the repository at this point in the history
Signed-off-by: macdonst <[email protected]>
  • Loading branch information
macdonst committed Oct 5, 2023
1 parent 042e0c5 commit 37833bb
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 39 deletions.
46 changes: 7 additions & 39 deletions app/api/$$.mjs
Original file line number Diff line number Diff line change
@@ -1,42 +1,10 @@
import data from '@begin/data'
import { checkRedirects } from '../lib/redirect.mjs'

const redirects = {
'/backend-workshop': '/workshop',
'/learn-backend': '/workshop',
'/backend': '/workshop',
}

const snakeToCamel = (str) =>
str
.toLowerCase()
.replace(/([-_][a-z])/g, (group) =>
group.toUpperCase().replace('-', '').replace('_', '')
)

export async function get(req) {
const path = req.requestContext.http.path
const isPath = Object.keys(redirects).includes(path)

if (isPath) {
let prop = path.startsWith('/') ? path.substring(1) : path
await data.incr({
table: 'views',
key: 'cta',
prop: snakeToCamel(prop),
})

return {
statusCode: 301,
headers: {
location: redirects[path],
},
}
} else {
return {
statusCode: 301,
headers: {
location: '/404',
},
}
async function catchAll() {
return {
statusCode: 302,
location: '/404',
}
}

export const get = [checkRedirects, catchAll]
35 changes: 35 additions & 0 deletions app/lib/redirect.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import data from '@begin/data'

const redirects = {
'/backend-workshop': '/workshop',
'/learn-backend': '/workshop',
'/backend': '/workshop',
}

const snakeToCamel = (str) =>
str
.toLowerCase()
.replace(/([-_][a-z])/g, (group) =>
group.toUpperCase().replace('-', '').replace('_', '')
)

export async function checkRedirects(req) {
const path = req.requestContext.http.path
const isPath = Object.keys(redirects).includes(path)

if (isPath) {
let prop = path.startsWith('/') ? path.substring(1) : path
await data.incr({
table: 'views',
key: 'cta',
prop: snakeToCamel(prop),
})

return {
statusCode: 302,
headers: {
location: redirects[path],
},
}
}
}

0 comments on commit 37833bb

Please sign in to comment.