Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

first commit #4

Open
wants to merge 2 commits into
base: template
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .env.example

This file was deleted.

52 changes: 38 additions & 14 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,50 @@
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const cors = require('cors');
const indexRouter = require('./routes/index');
const mongoose = require('mongoose');
require('dotenv/config');
const { sendResponse, AppError } = require("./helpers/utils.js");

const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const cors = require("cors");
const indexRouter = require("./routes/index");
const mongoose = require("mongoose");

require("dotenv").config();

const app = express();

app.use(cors());
app.use(logger('dev'));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, "public")));

// Connect to MONGODB
mongoose.connect(process.env.MONGO_URI, () => {
console.log('Connected to Database!');
});
const mongoURI = process.env.MONGO_URI;
// console.log(mongoURI, "ok");
mongoose
.connect(process.env.MONGO_URI)
.then(() => console.log(`DB connected`))
.catch((err) => console.log(err));

app.use('/', indexRouter);
app.use("/", indexRouter);

// catch 404 and forard to error handler
app.use((req, res, next) => {
const err = new AppError(404, "Not Found", "Bad Request");
next(err);
});

/* Initialize Error Handling */
app.use((err, req, res, next) => {
console.log("ERROR", err);
return sendResponse(
res,
err.statusCode ? err.statusCode : 500,
false,
null,
{ message: err.message },
err.isOperational ? err.errorType : "Internal Server Error"
);
});
module.exports = app;
106 changes: 84 additions & 22 deletions controllers/car.controller.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,99 @@
const mongoose = require('mongoose');
const Car = require('../models/Car');
const { sendResponse, AppError } = require("../helpers/utils.js");
const mongoose = require("mongoose");
const Car = require("../models/Car");
const carController = {};

carController.createCar = async (req, res, next) => {
try {
// YOUR CODE HERE
} catch (err) {
// YOUR CODE HERE
}
const { make, model, year, transmission_type, size, style, price } = req.body;
const info = {
make,
model,
year,
transmission_type,
size,
style,
price,
};
try {
// YOUR CODE HERE
// //always remember to control your inputs
if (!info) throw new AppError(402, "Bad Request", "Create car Error");

// //mongoose query
const created = await Car.create(info);
res
.status(200)
.send({ message: "Create Car Successfully!", data: created });
} catch (err) {
// YOUR CODE HERE
next(err);
}
};

carController.getCars = async (req, res, next) => {
try {
// YOUR CODE HERE
} catch (err) {
// YOUR CODE HERE
}
try {
// YOUR CODE HERE
let page = parseInt(req.query.page) || 1;
let limit = parseInt(req.query.limit) || 10;

const listOfFound = await Car.find({ isDeleted: false })
.sort({ createdAt: -1 })
.limit(limit)
.skip((page - 1) * limit);
const count = await Car.count({ isDeleted: false });
console.log(count);
const totalPages = Math.ceil(count / limit);

res.status(200).send({
message: "Get Car List Successfully!",
data: listOfFound,
page: page,
total: totalPages,
});
} catch (err) {
// YOUR CODE HERE
}
};

carController.editCar = async (req, res, next) => {
try {
// YOUR CODE HERE
} catch (err) {
// YOUR CODE HERE
}
const targetId = req.params.id;
const updateInfo = req.body;
const options = { new: true };
try {
// YOUR CODE HERE

const updated = await Car.findByIdAndUpdate(targetId, updateInfo, options);
res
.status(200)
.send({ message: "Update Car Successfully!", data: updated });
} catch (err) {
// YOUR CODE HERE
next(err);
}
};

carController.deleteCar = async (req, res, next) => {
try {
// YOUR CODE HERE
} catch (err) {
// YOUR CODE HERE
}
const targetId = req.params.id;
const options = { new: true };
try {
// YOUR CODE HERE
const deleted = await Car.findByIdAndUpdate(
targetId,
{ isDeleted: true },
options
);
sendResponse(
res,
200,
true,
{ data: "oke" },
null,
"Delete Car Successfully!"
);
} catch (err) {
// YOUR CODE HERE
next(err);
}
};

module.exports = carController;
25 changes: 25 additions & 0 deletions helpers/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const utilsHelper = {};

utilsHelper.sendResponse = (res, status, success, data, errors, message) => {
const response = {};
if (success) response.success = success;
if (data) response.data = data;
if (errors) response.errors = errors;
if (message) response.message = message;
return res.status(status).json(response);
};

class AppError extends Error {
constructor(statusCode, message, errorType) {
super(message);
this.statusCode = statusCode;
this.errorType = errorType;
// all errors using this class are operational errors.
this.isOperational = true;
// create a stack trace for debugging (Error obj, void obj to avoid stack polution)
Error.captureStackTrace(this, this.constructor);
}
}

utilsHelper.AppError = AppError;
module.exports = utilsHelper;
109 changes: 58 additions & 51 deletions models/Car.js
Original file line number Diff line number Diff line change
@@ -1,59 +1,66 @@
const mongoose = require('mongoose');
const mongoose = require("mongoose");
const carSchema = new mongoose.Schema(
{
make: {
type: String,
required: true,
},
model: {
type: String,
required: true,
},
release_date: {
type: Number,
min: 1900,
required: true,
},
transmission_type: {
type: String,
enum: ['MANUAL', 'AUTOMATIC', 'AUTOMATED_MANUAL', 'DIRECT_DRIVE', 'UNKNOWN'],
required: true,
},
size: {
type: String,
enum: ['Compact', 'Midsize', 'Large'],
required: true,
},
style: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
isDeleted: { type: Boolean, default: false, required: true },
},
{
timestamps: true,
}
{
make: {
type: String,
required: true,
},
model: {
type: String,
required: true,
},
year: {
type: Number,
min: 1900,
required: true,
},
transmission_type: {
type: String,
enum: [
"MANUAL",
"AUTOMATIC",
"AUTOMATED_MANUAL",
"DIRECT_DRIVE",
"UNKNOWN",
],
required: true,
},
size: {
type: String,
enum: ["Compact", "Midsize", "Large"],
required: true,
},
style: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
isDeleted: { type: Boolean, default: false, required: true },
},
{
timestamps: true,
collection: "cars",
}
);

carSchema.pre(/^find/, function (next) {
if (!('_conditions' in this)) return next();
if (!('isDeleted' in carSchema.paths)) {
delete this['_conditions']['all'];
return next();
}
if (!('all' in this['_conditions'])) {
//@ts-ignore
this['_conditions'].isDeleted = false;
} else {
delete this['_conditions']['all'];
}
next();
if (!("_conditions" in this)) return next();
if (!("isDeleted" in carSchema.paths)) {
delete this["_conditions"]["all"];
return next();
}
if (!("all" in this["_conditions"])) {
//@ts-ignore
this["_conditions"].isDeleted = false;
} else {
delete this["_conditions"]["all"];
}
next();
});

const Car = mongoose.model('Car', carSchema);
const Car = mongoose.model("cars", carSchema);

module.exports = Car;
Loading