Created
May 22, 2024 18:35
-
-
Save mayankchoubey/2ed89e945e3a2f06ff06e16d65d84260 to your computer and use it in GitHub Desktop.
Fastify - HTTP + DB read
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 { env } from "node:process"; | |
import { DataTypes, Sequelize } from "sequelize"; | |
const dbUser = env.dbUser; | |
const dbUserPass = env.dbUserPass; | |
const dbName = env.dbName; | |
const sequelize = new Sequelize( | |
`postgres://${dbUser}:${dbUserPass}@localhost:5432/${dbName}`, | |
{ | |
logging: false, | |
pool: { | |
max: 10, | |
min: 10, | |
}, | |
}, | |
); | |
await sequelize.authenticate(); | |
const User = sequelize.define("user", { | |
email: { | |
type: DataTypes.STRING, | |
primaryKey: true, | |
}, | |
first: DataTypes.STRING, | |
last: DataTypes.STRING, | |
city: DataTypes.STRING, | |
county: DataTypes.STRING, | |
}, { | |
timestamps: false, | |
}); | |
export async function getUser(userEmail) { | |
return await User.findOne({ | |
where: { | |
email: userEmail, | |
}, | |
}); | |
} |
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 { getUser } from "./service.mjs"; | |
export async function handleRequest(req, rep) { | |
const userEmail = req?.body?.userEmail; | |
if (!userEmail) { | |
return rep.code(400).send(); | |
} | |
const user = await getUser(userEmail); | |
if (!user) { | |
return rep.code(204).send(); | |
} | |
rep.send(user); | |
} |
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 Fastify from "fastify"; | |
import { handleRequest } from "./fastifyController.mjs"; | |
const app = Fastify({ | |
logger: false, | |
}); | |
app.post("/", handleRequest); | |
app.listen({ port: 3000 }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment