Skip to content
Snippets Groups Projects
Commit 2dda42b7 authored by elit04's avatar elit04
Browse files

Sequelize Database in Typescript

parent 0800fd64
No related branches found
No related tags found
No related merge requests found
const { Sequelize } = require("sequelize");
import { Dialect, Sequelize } from "sequelize";
const dbName = process.env.DB_NAME;
const dbUser = process.env.DB_USER;
const dbHost = process.env.DB_HOST;
const dbDriver = process.env.DB_DRIVER;
const dbDriver = process.env.DB_DRIVER as Dialect;
const dbPassword = process.env.DB_PASSWORD;
if (!dbName || !dbUser || !dbHost || !dbDriver || !dbPassword) {
......@@ -18,4 +18,4 @@ const sequelizeConnection = new Sequelize(dbName, dbUser, dbPassword, {
logging: false,
});
module.exports = sequelizeConnection;
export default sequelizeConnection;
const Customer = require("./models/customer");
const Boat = require("./models/boat");
const Person = require("./models/person");
const Checkin = require("./models/checkin");
const Checkout = require("./models/checkout");
import Customer from "./models/Customer";
import Boat from "./models/Boat";
import Worker from "./models/Worker";
import CheckIn from "./models/CheckIn";
const isDev = process.env.NODE_ENV === "development";
......@@ -10,9 +9,8 @@ const dbInit = () =>
Promise.all([
Customer.sync({ alter: isDev }),
Boat.sync({ alter: isDev }),
Person.sync({ alter: isDev }),
Checkin.sync({ alter: isDev }),
Checkout.sync({ alter: isDev }),
Worker.sync({ alter: isDev }),
CheckIn.sync({ alter: isDev }),
]);
module.exports = dbInit;
export default dbInit;
import sequelizeConnection from "../config";
import { DataTypes, Model, Optional } from "sequelize";
interface BoatAttributes {
id: number;
name: string;
status: boolean;
active: boolean;
seats: number;
}
export interface BoatAttributesInput extends Optional<BoatAttributes, "id"> {}
export interface BoatAttributesOutput extends Required<BoatAttributes> {}
class Boat extends Model<BoatAttributes> implements BoatAttributes {
public id!: number;
public name!: string;
public status: boolean;
public active: boolean;
public seats: number;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
Boat.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
},
name: {
type: new DataTypes.STRING(),
allowNull: false,
},
status: {
type: DataTypes.BOOLEAN,
allowNull: false,
},
active: {
type: DataTypes.BOOLEAN,
allowNull: false,
},
seats: {
type: new DataTypes.INTEGER(),
allowNull: false,
},
},
{
tableName: "boat",
sequelize: sequelizeConnection,
}
);
export const create = async (payload: Boat): Promise<BoatAttributesOutput> => {
return await Boat.create(payload);
};
export const update = async (
id: number,
payload: Partial<BoatAttributesInput>
): Promise<BoatAttributesOutput> => {
const boat = await Boat.findByPk(id);
if (!boat) {
throw new Error("not found");
}
return await (boat as Boat).update(payload);
};
export const getById = async (id: number): Promise<Boat> => {
const boat = await Boat.findByPk(id);
if (!boat) {
throw new Error("not found");
}
return boat;
};
export const deleteById = async (id: number): Promise<boolean> => {
const deletedBoatCount = await Boat.destroy({
where: { id },
});
return !!deletedBoatCount;
};
export const getAll = async (): Promise<BoatAttributesOutput[]> => {
return Boat.findAll();
};
export const BoatService = {
create,
update,
getById,
deleteById,
getAll,
};
export default Boat;
import sequelizeConnection from "../config";
import { DataTypes, Model, Optional } from "sequelize";
interface CheckInAttributes {
id: number;
checkin: Date;
checkout: Date;
clientID: number;
boatID: number;
destination: string;
note: string;
}
export interface CheckInAttributesInput
extends Optional<CheckInAttributes, "id"> {}
export interface CheckInAttributesOutput extends Required<CheckInAttributes> {}
class CheckIn extends Model<CheckInAttributes> implements CheckInAttributes {
public id!: number;
public checkin: Date;
public checkout: Date;
public clientID: number;
public boatID: number;
public destination: string;
public note: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
CheckIn.init(
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
},
checkin: {
type: DataTypes.DATE,
allowNull: false,
// primaryKey: true,
},
checkout: {
type: DataTypes.DATE,
allowNull: false,
// primaryKey: true
},
clientID: {
type: DataTypes.INTEGER,
// primaryKey: true,
references: {
model: "customer",
key: "id",
},
},
boatID: {
type: DataTypes.INTEGER,
references: {
model: "boat",
key: "id",
},
},
destination: {
type: new DataTypes.STRING(),
},
note: {
type: new DataTypes.STRING(),
},
},
{
tableName: "checkIn",
sequelize: sequelizeConnection,
}
);
export const create = async (
payload: CheckIn
): Promise<CheckInAttributesOutput> => {
return await CheckIn.create(payload);
};
export const update = async (
id: number,
payload: Partial<CheckInAttributesInput>
): Promise<CheckInAttributesOutput> => {
const checkin = await CheckIn.findByPk(id);
if (!checkin) {
throw new Error("not found");
}
return await (checkin as CheckIn).update(payload);
};
export const getById = async (id: number): Promise<CheckIn> => {
const checkin = await CheckIn.findByPk(id);
if (!checkin) {
throw new Error("not found");
}
return checkin;
};
const deleteById = async (id: number): Promise<boolean> => {
const deletedCheckInCount = await CheckIn.destroy({
where: { id },
});
return !!deletedCheckInCount;
};
export const getAll = async (): Promise<CheckInAttributesOutput[]> => {
return CheckIn.findAll();
};
export const CheckInService = {
create,
update,
getById,
deleteById,
getAll,
};
export default CheckIn;
import sequelizeConnection from "../config";
import { DataTypes, Model, Optional } from "sequelize";
interface CustomerAttributes {
id: number;
firstName: string;
lastName: string;
email: string;
}
export interface CustomerInput extends Optional<CustomerAttributes, "id"> {}
export interface CustomerOutput extends Required<CustomerAttributes> {}
class Customer extends Model<CustomerAttributes> implements CustomerAttributes {
public id!: number;
public firstName!: string;
public lastName: string;
public email: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
Customer.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
firstName: {
type: new DataTypes.STRING(),
allowNull: false,
},
lastName: {
type: new DataTypes.STRING(),
allowNull: false,
},
email: {
type: new DataTypes.STRING(),
allowNull: false,
unique: true,
},
},
{
tableName: "customer",
sequelize: sequelizeConnection,
}
);
export const create = async (payload: Customer): Promise<CustomerOutput> => {
return await Customer.create(payload);
};
export const update = async (
id: number,
payload: Partial<CustomerInput>
): Promise<CustomerOutput> => {
const customer = await Customer.findByPk(id);
if (!customer) {
throw new Error("not found");
}
return await (customer as Customer).update(payload);
};
export const getById = async (id: number): Promise<CustomerInput> => {
const customer = await Customer.findByPk(id);
if (!customer) {
throw new Error("not found");
}
return customer;
};
const deleteById = async (id: number): Promise<boolean> => {
const deletedCustomerCount = await Customer.destroy({
where: { id },
});
return !!deletedCustomerCount;
};
export const getAll = async (): Promise<CustomerOutput[]> => {
return Customer.findAll();
};
export const CustomerService = {
create,
update,
getById,
deleteById,
getAll,
};
export default Customer;
import sequelizeConnection from "../config";
import { DataTypes, Model, Optional } from "sequelize";
interface WorkerAttributes {
email: string;
firstName: string;
lastName: string;
password: string;
role: string;
}
export interface WorkerInput extends Optional<WorkerAttributes, "email"> {}
export interface WorkerOutput extends Required<WorkerAttributes> {}
class Worker extends Model<WorkerAttributes> implements WorkerAttributes {
public email!: string;
public firstName: string;
public lastName: string;
public password: string;
public role: string;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
Worker.init(
{
email: {
type: new DataTypes.STRING(),
allowNull: false,
primaryKey: true,
unique: true,
},
firstName: {
type: new DataTypes.STRING(),
allowNull: false,
},
lastName: {
type: new DataTypes.STRING(),
allowNull: false,
},
password: {
type: new DataTypes.STRING(),
allowNull: false,
},
role: {
type: new DataTypes.STRING(),
allowNull: false,
},
},
{
tableName: "worker",
sequelize: sequelizeConnection,
}
);
export const create = async (payload: Worker): Promise<WorkerOutput> => {
return await Worker.create(payload);
};
export const update = async (
email: string,
payload: Partial<WorkerInput>
): Promise<WorkerOutput> => {
const worker = await Worker.findByPk(email);
if (!worker) {
throw new Error("not found");
}
return await (worker as Worker).update(payload);
};
export const getById = async (email: string): Promise<WorkerInput> => {
const worker = await Worker.findByPk(email);
if (!worker) {
throw new Error("not found");
}
return worker;
};
const deleteById = async (email: string): Promise<boolean> => {
const deletedWorkerCount = await Worker.destroy({
where: { email },
});
return !!deletedWorkerCount;
};
export const getAll = async (): Promise<WorkerOutput[]> => {
return Worker.findAll();
};
export const WorkerService = {
create,
update,
getById,
deleteById,
getAll,
};
export default Worker;
const Sequelize = require("sequelize");
const db = require("../config");
const Boat = db.define(
"boat",
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
name: {
allowNull: false,
type: Sequelize.STRING,
},
status: {
allowNull: false,
type: Sequelize.BOOLEAN,
},
active: {
allowNull: false,
type: Sequelize.BOOLEAN,
},
class: {
allowNull: false,
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
},
{ freezeTableName: true } //to force keeping chosen table-names
);
module.exports = Boat;
const Sequelize = require("sequelize");
const db = require("../config");
const Checkin = db.define(
"checkin",
{
startTime: {
primaryKey: true,
type: Sequelize.DATE,
},
endTime: {
primaryKey: true,
type: Sequelize.DATE,
},
clientID: {
primaryKey: true,
type: Sequelize.INTEGER,
references: {
model: "customer",
key: "id",
},
},
boatID: {
// primaryKey: true,
type: Sequelize.INTEGER,
references: {
model: "boat",
key: "id",
},
},
destination: {
type: Sequelize.STRING,
},
note: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
},
{ freezeTableName: true } //to force keeping chosen table-names
);
module.exports = Checkin;
const Sequelize = require("sequelize");
const db = require("../config");
const Checkout = db.define(
"checkout",
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
clientId: {
type: Sequelize.INTEGER,
// primaryKey: true,
type: Sequelize.INTEGER,
references: {
model: "customer",
key: "id",
},
},
boatId: {
type: Sequelize.INTEGER,
// primaryKey: true,
type: Sequelize.INTEGER,
references: {
model: "boat",
key: "id",
},
},
timeStamp: {
type: Sequelize.DATE,
primaryKey: true,
},
note: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
},
{ freezeTableName: true } //to force keeping chosen table-names
);
module.exports = Checkout;
const Sequelize = require("sequelize");
const db = require("../config");
const Customer = db.define(
"customer",
{
//attributes
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
firstName: {
allowNull: false,
type: Sequelize.STRING,
},
lastName: {
allowNull: false,
type: Sequelize.STRING,
},
email: {
allowNull: false,
type: Sequelize.STRING,
},
},
{ freezeTableName: true } //to force keeping chosen table-names
);
module.exports = Customer;
const Sequelize = require("sequelize");
const db = require("../config");
const Person = db.define(
"person",
{
email: {
type: Sequelize.STRING,
primaryKey: true,
},
firstName: {
type: Sequelize.STRING,
},
lastName: {
type: Sequelize.STRING,
},
pass: {
type: Sequelize.STRING,
},
role: {
type: Sequelize.STRING,
},
createdAt: {
allowNull: false,
type: Sequelize.DATE,
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE,
},
},
{ freezeTableName: true } //to force keeping chosen table-names
);
module.exports = Person;
// import * as express from 'express';
import * as express from "express";
import { UserService } from "./db/models/User";
import { VehicleTypeService } from "./db/models/VehicleTypes";
// const router = express.Router();
const router = express.Router();
// // Vehicle Type
// router.get('/api/vehicleType/:id', async (req, res) => {
// const id = Number(req.params.id)
// const result = await VehicleTypeService.getById(id)
// return res.status(200).send(result)
// });
// router.post('/api/vehicleType/', async (req, res) => {
// const payload = req.body
// const result = await VehicleTypeService.create(payload)
// return res.status(200).send(result)
// });
// router.put('/api/vehicleType/:id', async (req, res) => {
// const id = Number(req.params.id)
// const payload = req.body
// const result = await VehicleTypeService.update(id, payload)
// return res.status(201).send(result)
// });
// router.delete('/api/vehicleType/:id', async (req, res) => {
// const id = Number(req.params.id)
// const result = await VehicleTypeService.deleteById(id)
// return res.status(204).send({
// success: result
// })
// });
// router.get('/api/vehicleType/', async (req, res) => {
// const results = await VehicleTypeService.getAll()
// return res.status(200).send(results)
// });
// Vehicle Type
router.get("/api/vehicleType/:id", async (req, res) => {
const id = Number(req.params.id);
const result = await VehicleTypeService.getById(id);
return res.status(200).send(result);
});
router.post("/api/vehicleType/", async (req, res) => {
const payload = req.body;
const result = await VehicleTypeService.create(payload);
return res.status(200).send(result);
});
router.put("/api/vehicleType/:id", async (req, res) => {
const id = Number(req.params.id);
const payload = req.body;
const result = await VehicleTypeService.update(id, payload);
return res.status(201).send(result);
});
router.delete("/api/vehicleType/:id", async (req, res) => {
const id = Number(req.params.id);
const result = await VehicleTypeService.deleteById(id);
return res.status(204).send({
success: result,
});
});
router.get("/api/vehicleType/", async (req, res) => {
const results = await VehicleTypeService.getAll();
return res.status(200).send(results);
});
// // USER
// router.get('/api/user/:id', async (req, res) => {
// const id = Number(req.params.id)
// const result = await UserService.getById(id)
// return res.status(200).send(result)
// });
// router.post('/api/user/', async (req, res) => {
// const payload = req.body
// const result = await UserService.create(payload)
// return res.status(200).send(result)
// });
// router.put('/api/user/:id', async (req, res) => {
// const id = Number(req.params.id)
// const payload = req.body
// const result = await UserService.update(id, payload)
// return res.status(201).send(result)
// });
// router.delete('/api/user/:id', async (req, res) => {
// const id = Number(req.params.id)
// const result = await UserService.deleteById(id)
// return res.status(204).send({
// success: result
// })
// });
// router.get('/api/user/', async (req, res) => {
// const results = await UserService.getAll()
// return res.status(200).send(results)
// });
// USER
router.get("/api/user/:id", async (req, res) => {
const id = Number(req.params.id);
const result = await UserService.getById(id);
return res.status(200).send(result);
});
router.post("/api/user/", async (req, res) => {
const payload = req.body;
const result = await UserService.create(payload);
return res.status(200).send(result);
});
router.put("/api/user/:id", async (req, res) => {
const id = Number(req.params.id);
const payload = req.body;
const result = await UserService.update(id, payload);
return res.status(201).send(result);
});
router.delete("/api/user/:id", async (req, res) => {
const id = Number(req.params.id);
const result = await UserService.deleteById(id);
return res.status(204).send({
success: result,
});
});
router.get("/api/user/", async (req, res) => {
const results = await UserService.getAll();
return res.status(200).send(results);
});
// // Other TODO
// /*
// router.get('/api/login', (req, res) => {
// console.log(req.body)
// res.json({'success': true, data: []});
// });
// */
// router.post('/api/logEntry', (req, res) => {
// console.log(req.body)
// res.json({'success': true});
// });
// Other TODO
/*
router.get('/api/login', (req, res) => {
console.log(req.body)
res.json({'success': true, data: []});
});
*/
router.post("/api/logEntry", (req, res) => {
console.log(req.body);
res.json({ success: true });
});
// export default router;
export default router;
require("dotenv/config");
const express = require("express");
const dbInit = require("./db/db_init");
//const apiRou = require("./routes");
import "dotenv/config";
import express from "express";
import dbInit from "./db/db_init";
//import apiRouter from "./routes";
let init = async () => {
await dbInit();
const app = express();
app.use(express.json());
// app.use(apiRouter);
//app.use(apiRouter);
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server listening on port: ${port}`));
};
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment