Skip to content

Commit

Permalink
Working API's
Browse files Browse the repository at this point in the history
  • Loading branch information
BryanField15 committed Oct 24, 2023
1 parent 7f5a8ef commit c8da29a
Show file tree
Hide file tree
Showing 11 changed files with 488 additions and 25 deletions.
32 changes: 27 additions & 5 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,34 @@
/* eslint-disable no-console */
const express = require('express');
const morgan = require('morgan');

const tripRouter = require('./routes/tripRoutes');
const userRouter = require('./routes/userRoutes');

const app = express();

app.get('/', (req, res) => {
res.status(200).json('Hello from the giddyup server!');
//1) MIDDLESWARES
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}

// Middleware to accept json on POST requests
app.use(express.json());

// 2) Routes
app.use('/api/v1/trips', tripRouter);
app.use('/api/v1/users', userRouter);

app.all('*', (req, res, next) => {
res.status(404).json({
status: 'fail',
message: `Can't find ${req.originalUrl} on this server`,
});
});

const port = 3000;
app.listen(port, () => {
console.log(`Giddyup is galloping on port ${port}`);
app.use((err, req, res, next) => {
err.statusCode = err.statusCode || 500;
err.status = err.staus || 'error';
});

module.exports = app;
108 changes: 108 additions & 0 deletions controllers/tripController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
const Trip = require('../models/tripModel');
const APIFeatures = require('../utils/apiFeatures');

exports.aliasTopTrips = (req, res, next) => {
req.query.limit = '5';
req.query.sort = '-departureTime, -ratingsAverage';
req.query.fields = 'name, departureTime, ratingsAverage';
next();
};

exports.getAllTrips = async (req, res) => {
try {
// EXECUTE QUERY
const features = new APIFeatures(Trip.find(), req.query)
.filter()
.sort()
.limitFields()
.paginate();
const trips = await features.query;

// SEND RESPONSE
res.status(200).json({
status: 'success',
results: trips.length,
data: {
trips,
},
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};

exports.getTrip = async (req, res) => {
try {
const trip = await Trip.findById(req.params.id);

res.status(200).json({
status: 'success',
data: {
trip,
},
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};

exports.createTrip = async (req, res) => {
try {
const newTrip = await Trip.create(req.body);

res.status(201).json({
status: 'success',
data: {
trip: newTrip,
},
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err,
});
}
};

exports.updateTrip = async (req, res) => {
try {
const trip = await Trip.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
});

res.status(200).json({
status: 'success',
data: {
trip,
},
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};

exports.deleteTrip = async (req, res) => {
try {
await Trip.findByIdAndDelete(req.params.id);

res.status(204).json({
status: 'success',
data: null,
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};
99 changes: 99 additions & 0 deletions controllers/userController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
const User = require('../models/userModel');
const APIFeatures = require('../utils/apiFeatures');

exports.getAllUsers = async (req, res) => {
try {
const features = new APIFeatures(User.find(), req.query)
.filter()
.sort()
.limitFields()
.paginate();
const users = await features.query;

res.status(200).json({
status: 'success',
results: users.length,
data: {
users,
},
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};

exports.getUser = async (req, res) => {
try {
const user = await User.findById(req.params.id);

res.status(200).json({
status: 'success',
data: {
user,
},
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};

exports.createUser = async (req, res) => {
try {
const newUser = await User.create(req.body);

res.status(201).json({
status: 'success',
data: {
user: newUser,
},
});
} catch (err) {
res.status(400).json({
status: 'fail',
message: err,
});
}
};

exports.updateUser = async (req, res) => {
try {
const user = await User.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
});

res.status(200).json({
status: 'success',
data: {
user,
},
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};

exports.deleteUser = async (req, res) => {
try {
await User.findByIdAndDelete(req.params.id);

res.status(204).json({
status: 'success',
data: null,
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err,
});
}
};
57 changes: 57 additions & 0 deletions dev-data/data/trips.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
{
"trips": [
{
"id": "1",
"driver": {
"id": "101",
"name": "John Doe",
"car": "Toyota Camry",
"availableSeats": 2
},
"departure": "Seddon",
"destination": "Workplace A",
"pickupLocations": ["Location A", "Location B"],
"passengers": [
{
"id": "201",
"name": "Alice Johnson"
},
{
"id": "202",
"name": "Bob Smith"
}
]
},
{
"id": "2",
"driver": {
"id": "102",
"name": "Jane Smith",
"car": "Honda Civic",
"availableSeats": 3
},
"departure": "Yarraville",
"destination": "Workplace B",
"pickupLocations": ["Location C", "Location D"],
"passengers": [
{
"id": "203",
"name": "Charlie Brown"
}
]
},
{
"id": "3",
"driver": {
"id": "103",
"name": "Eva Williams",
"car": "Ford Fusion",
"availableSeats": 1
},
"departure": "Footscray",
"destination": "Workplace C",
"pickupLocations": ["Location E"],
"passengers": []
}
]
}
16 changes: 16 additions & 0 deletions models/tripModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose = require('mongoose');

const tripSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A trip must have a name'],
unique: true,
trim: true,
maxlength: [40, 'A trip name must have less or equal then 40 characters'],
minlength: [10, 'A trip name must have more or equal then 10 characters'],
},
});

const Trip = mongoose.model('Trip', tripSchema);

module.exports = Trip;
16 changes: 16 additions & 0 deletions models/userModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A user must have a name'],
unique: true,
trim: true,
maxlength: [40, 'A user name must have less or equal then 40 characters'],
minlength: [10, 'A user name must have more or equal then 10 characters'],
},
});

const User = mongoose.model('User', userSchema);

module.exports = User;
Loading

0 comments on commit c8da29a

Please sign in to comment.