Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Created January 14, 2024 05:32
Show Gist options
  • Select an option

  • Save mayankchoubey/e8bd92931339ba9a3013b7fc786cd672 to your computer and use it in GitHub Desktop.

Select an option

Save mayankchoubey/e8bd92931339ba9a3013b7fc786cd672 to your computer and use it in GitHub Desktop.
Node.js Postgres database read application in various frameworks
/*
COMMON FILE FOR EXPRESS, FASTIFY, KOA, HAPI, RESTIFY, AND HYPER EXPRESS APPS
*/
import { DataTypes, Sequelize } from "sequelize";
const dbUser = process.env.dbUser;
const dbUserPass = process.env.dbUserPass;
const dbName = process.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,
age: DataTypes.INTEGER,
}, {
timestamps: false,
});
export async function getUser(email) {
let out = {};
const user = await User.findOne({
where: {
email,
},
});
if (user) {
const o = user.dataValues;
Object.keys(o).forEach((k) =>
o[k] = typeof o[k] == "string" ? o[k].trim() : o[k]
);
out = o;
}
return out;
}
/*
EXPRESS APP
*/
import express from "express";
import { getUser } from "./db.mjs";
const app = express();
app.use(express.json());
app.post("/", async (req, res) => {
if (!(req.body && req.body.email)) {
return res.status(400).send();
}
const email = req.body.email;
const user = await getUser(email);
res.json(user);
});
app.listen(3000);
/*
FASTIFY APP
*/
import Fastify from "fastify";
import { getUser } from "./db.mjs";
const app = Fastify({
logger: false,
});
app.post("/", async (req, res) => {
if (!(req.body && req.body.email)) {
return res.code(400).send();
}
const email = req.body.email;
const user = await getUser(email);
res.send(user);
});
app.listen({ port: 3000 });
/*
HAPI APP
*/
import Hapi from "@hapi/hapi";
import { getUser } from "./db.mjs";
const server = Hapi.server({
port: 3000,
host: "127.0.0.1",
});
const reqHandler = async (req, h) => {
if (!(req.payload && req.payload.email)) {
return h.code(400).send();
}
const email = req.payload.email;
const user = await getUser(email);
return h.response(user);
};
server.route({
method: "POST",
path: "/",
handler: reqHandler,
});
server.start();
/*
HYPER EXPRESS APP
*/
import HyperExpress from "hyper-express";
import { getUser } from "./db.mjs";
const webserver = new HyperExpress.Server();
const reqHandler = async (request, response) => {
const reqBody = await request.json();
if (!(reqBody && reqBody.email)) {
return response.status(400).send();
}
const email = reqBody.email;
const user = await getUser(email);
response.json(user);
};
webserver.post("/", reqHandler);
webserver.listen(3000);
/*
KOA APP
*/
import Koa from "koa";
import Router from "@koa/router";
import { bodyParser } from "@koa/bodyparser";
import { getUser } from "./db.mjs";
const app = new Koa();
const router = new Router();
router.post("/", async (ctx, next) => {
if (!(ctx.request && ctx.request.body && ctx.request.body.email)) {
return ctx.response.status = 400;
}
const email = ctx.request.body.email;
const user = await getUser(email);
ctx.response.body = user;
});
app
.use(bodyParser())
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000);
/*
NEST APP
*/
// ----------------------
// main.ts
// ----------------------
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
// ----------------------
// app.module.ts
// ----------------------
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { join } from "path";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { User } from "./user.entity";
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: "postgres",
host: process.env.DATABASE_HOST,
port: 5432,
username: process.env.dbUser,
password: process.env.dbPass,
database: process.env.dbName,
entities: [join(__dirname, "**", "*.entity.{ts,js}")],
synchronize: false,
}),
TypeOrmModule.forFeature([User]),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
// ----------------------
// app.controller.ts
// ----------------------
import {
Controller,
HttpException,
HttpStatus,
Post,
Request,
} from "@nestjs/common";
import { AppService } from "./app.service";
import { User } from "./user.entity";
@Controller()
export class AppController {
constructor(
private readonly appService: AppService,
) {}
@Post("/")
async getUser(@Request() request): Promise<User> {
if (!(request.body && request.body.email)) {
throw new HttpException("Bad request", HttpStatus.BAD_REQUEST);
}
const email = request.body.email;
const user = await this.appService.getUser(email);
return user;
}
}
// ----------------------
// app.service.ts
// ----------------------
import { Injectable } from "@nestjs/common";
import { User } from "./user.entity";
import { Repository } from "typeorm";
import { InjectRepository } from "@nestjs/typeorm";
@Injectable()
export class AppService {
constructor(
@InjectRepository(User) private userRepository: Repository<User>,
) {}
async getUser(email: string): Promise<User> {
const user = await this.userRepository.findOne({
where: { email },
});
if (user) {
Object.keys(user).forEach((k) =>
user[k] = typeof user[k] == "string" ? user[k].trim() : user[k]
);
}
return user;
}
}
// ----------------------
// user.entity.ts
// ----------------------
import { BaseEntity, Column, Entity, PrimaryColumn } from "typeorm";
@Entity("users")
export class User extends BaseEntity {
@PrimaryColumn()
email: string;
@Column()
first: string;
@Column()
last: string;
@Column()
city: string;
@Column()
county: string;
@Column()
age: number;
}
/*
NEST FASTIFY APP
*/
/*
THE ONLY FILE DIFFERENT FROM NEST APP IS MAIN.TS
*/
// ----------------------
// main.ts
// ----------------------
import { NestFactory } from "@nestjs/core";
import {
FastifyAdapter,
NestFastifyApplication,
} from "@nestjs/platform-fastify";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
await app.listen(3000);
}
bootstrap();
/*
RESTIFY APP
*/
import restify from "restify";
import { getUser } from "./db.mjs";
var server = restify.createServer();
server.use(restify.plugins.bodyParser());
server.post("/", async (req, res) => {
if (!(req.body && req.body.email)) {
return res.code(400).send();
}
const email = req.body.email;
const user = await getUser(email);
res.send(user);
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment