Commit 8e6785c8 by Farhaan Khan

Initial commit - Fastify backend with Sequelize and TypeScript

parents
# Node modules
node_modules/
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# TypeScript
dist/
*.tsbuildinfo
# Env files
.env
# IDEs
.vscode/
.idea/
# OS-specific
.DS_Store
Thumbs.db
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "ts-node-dev --respawn src/index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/node": "^22.15.3",
"ts-node-dev": "^2.0.0",
"typescript": "^5.8.3"
},
"dependencies": {
"fastify": "^5.3.2",
"fastify-cors": "^6.0.3",
"fastify-plugin": "^5.0.1",
"mysql2": "^3.14.1",
"pg-hstore": "^2.3.4",
"sequelize": "^6.37.7",
"sequelize-typescript": "^2.1.6",
"zod": "^3.24.4"
}
}
import Fastify from 'fastify';
import db from './plugins/db';
import userRoutes from './routes/user';
const app = Fastify();
app.register(db);
app.register(userRoutes, { prefix: '/api/users' });
app.listen({ port: 3001 }, (err) => {
if (err) throw err;
console.log('Server running on http://localhost:3001');
});
import { Table, Column, Model, DataType } from 'sequelize-typescript';
@Table
export class User extends Model {
@Column({
type: DataType.STRING,
allowNull: false,
})
name!: string;
@Column({
type: DataType.STRING,
allowNull: false,
unique: true,
})
email!: string;
}
import { FastifyPluginAsync } from 'fastify';
import { Sequelize } from 'sequelize-typescript';
const dbPlugin: FastifyPluginAsync = async (fastify) => {
const sequelize = new Sequelize({
database: 'product_db',
username: 'root',
password: 'Faruskhan@985',
host: 'localhost',
dialect: 'mysql',
models: [__dirname + '/../models'], // Make sure this path is correct
});
try {
await sequelize.sync();
console.log('Sequelize connected successfully');
// Optionally attach sequelize instance to Fastify
fastify.decorate('sequelize', sequelize);
} catch (err) {
console.error('Error connecting to DB:', err);
}
};
export default dbPlugin;
import { FastifyPluginAsync } from 'fastify';
import { z } from 'zod';
import { User } from '../models/User';
const userSchema = z.object({
name: z.string(),
email: z.string().email()
});
const userRoutes: FastifyPluginAsync = async (fastify) => {
fastify.post('/', async (req, res) => {
const parsed = userSchema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).send(parsed.error);
}
const user = await User.create(parsed.data);
res.send(user);
});
};
export default userRoutes;
{
"compilerOptions": {
"target": "ES2022", // Or ES2020+, avoid ESNext for now
"module": "CommonJS",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment