Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Created May 22, 2024 18:35
Show Gist options
  • Save mayankchoubey/2ed89e945e3a2f06ff06e16d65d84260 to your computer and use it in GitHub Desktop.
Save mayankchoubey/2ed89e945e3a2f06ff06e16d65d84260 to your computer and use it in GitHub Desktop.
Fastify - HTTP + DB read
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,
},
});
}
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);
}
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