REST API Server - sandeepganapatimore/webatool GitHub Wiki
Introduction
Environment Setup
Install Nodejs
Create Project
Install Packages
npm install sequelize
npm install express
npm install nodemon
Create a Simple Express Server
This is the simple express application.
import app from "./src/app";
const port = 8000;
app.get("/api", (req, res) => {
res.send("App is running");
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Folder Structure & File Structure
Server.ts
import app from "./src/app";
const port = 8000;
app.get("/api", (req, res) => {
res.send("App is running");
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
App.ts
import express from "express";
import routes from "./routes";
import cors from 'cors';
class App {
myLogger(req, res, next) {
console.log("LOGGED");
next();
}
app = express();
constructor() {
this.app.use(express.json());
this.app.use(this.myLogger);
this.app.use(cors());
this.app.use("/api", routes);
}
}
export default new App().app;
Routes.ts
import express from "express";
import scanRoutes from "./scans/scanRoute";
class Routes {
routes = express.Router();
constructor() {
this.routes.use("/", scanRoutes);
}
}
export default new Routes().routes;
db.ts
import { Sequelize } from "sequelize";
const sequelize = new Sequelize("rapdb", "appdev", "dev123", {
host: "localhost",
dialect: "mysql",
logging: false,
});
Check the connections
async function connect() {
try {
await sequelize.authenticate();
console.log("Connection has been established successfully.");
} catch (error) {
console.error("Unable to connect to the database:", error);
}
}
const synDb = () => {
connect();
sequelize
.sync()
.then(() => {
console.log("Scan table created successfully!");
})
.catch((error) => {
console.error("Unable to create table : ", error);
});
};
to call execute function
synDb();
export default sequelize;