Created
August 3, 2019 09:42
-
-
Save cagdas1/a7d2ea0c9e03fa3a64a7a8d79fc9b220 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { APIGatewayEvent, Context, Callback } from "aws-lambda"; | |
import { connectToDB, success, redirect, notFound } from "./lib"; | |
import { MongoClient } from "mongodb"; | |
const DB_NAME = process.env.DB_NAME as string; | |
let dbClient: MongoClient; | |
export async function handler(event: APIGatewayEvent, context: Context, callback: Callback) { | |
try { | |
dbClient = await connectToDB(); | |
const db = dbClient.db(DB_NAME); | |
const id = event.pathParameters!["id"]; | |
const dbItem = await db.collection("urls").findOne({shortId: id}); | |
if(!dbItem) { | |
return callback(null, notFound({})); | |
} | |
return callback(null, redirect(dbItem.url)); | |
} catch(err) { | |
console.error(err); | |
return callback("Internal error"); | |
} finally { | |
await dbClient.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment