Skip to content

Commit

Permalink
Added routes.
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbeutler committed Sep 11, 2021
1 parent 803c2c5 commit e95c741
Show file tree
Hide file tree
Showing 9 changed files with 258 additions and 71 deletions.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export default async function startServer() {
################################################
`);
})
.on('error', err => {
.on('error', (err) => {
Logger.error(err);
process.exit(1);
});
Expand Down
4 changes: 4 additions & 0 deletions src/loaders/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import cors from 'cors';
import express, { Application, Request, Response } from 'express';
import morgan from 'morgan';
import usersRoute from '../routes/users.route';
import festivalRoute from '../routes/festivals.route';
import festivalUserRoute from '../routes/festival-user.route';

export default async ({ app }: { app: Application }) => {
app.use(express.json());
Expand All @@ -19,4 +21,6 @@ export default async ({ app }: { app: Application }) => {
app.enable('trust proxy');

app.use('/users', usersRoute);
app.use('/festivals', festivalRoute);
app.use('/festival-users', festivalUserRoute);
};
37 changes: 14 additions & 23 deletions src/models/Festival.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,24 @@ import { Schema, model } from 'mongoose';
import { Festival } from '../interfaces/models';

const schema = new Schema<Festival>({
name: { type: String, required: true },
description: String,
location: String
})
name: { type: String, required: true },
description: String,
location: String,
});

const FestivalModel = model<Festival>('Festival', schema)
const FestivalModel = model<Festival>('Festival', schema);

const getFestivalById = async (id: string) => {
return FestivalModel.findById(id).exec();
}
const getFestivalById = async (id: string) => FestivalModel.findById(id).exec();

const getAllFestivals = async () => {
return FestivalModel.find();
}
const getAllFestivals = async () => FestivalModel.find();

const createFestival = async (festivalObj: any) => FestivalModel.create(festivalObj);

const createFestival = async (festivalObj: any) => {
return FestivalModel.create(festivalObj)
}

const updateFestivalByID = async (id: String, festivalObj: any) => {
return FestivalModel.findByIdAndUpdate(id, festivalObj, { new: true })
}
const updateFestivalByID = async (id: String, festivalObj: any) => FestivalModel.findByIdAndUpdate(id, festivalObj, { new: true });

export {
getFestivalById,
getAllFestivals,
createFestival,
updateFestivalByID
}
getFestivalById,
getAllFestivals,
createFestival,
updateFestivalByID,
};
28 changes: 13 additions & 15 deletions src/models/FestivalUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,22 @@ import { Schema, model } from 'mongoose';
import { FestivalUser } from '../interfaces/models';

const schema = new Schema<FestivalUser>({
festival: { type: Schema.Types.ObjectId, ref: 'Festival', required: true },
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
balance: { type: Number, required: true, default: 0 },
role: { type: String, enum: ["visitor", "employee", "orgianisator"], required: true, default: 'visitor' },
imageUrl: String
})
festival: { type: Schema.Types.ObjectId, ref: 'Festival', required: true },
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
balance: { type: Number, required: true, default: 0 },
role: {
type: String, enum: ['visitor', 'employee', 'orgianisator'], required: true, default: 'visitor',
},
imageUrl: String,
});

const FestivalUserModel = model<FestivalUser>('FestivalUser', schema);

const getFestivalUserById = async (id: String) => {
return FestivalUserModel.findById(id).populate('user').exec()
}
const getFestivalUserById = async (id: String) => FestivalUserModel.findById(id).populate('user').exec();

const createFestivaluser = async (festivalUserObj: any) => {
return FestivalUserModel.create(festivalUserObj)
}
const createFestivaluser = async (festivalUserObj: any) => FestivalUserModel.create(festivalUserObj);

export {
getFestivalUserById,
createFestivaluser
}
getFestivalUserById,
createFestivaluser,
};
20 changes: 9 additions & 11 deletions src/models/Payment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,17 @@ import { Schema, model } from 'mongoose';
import { Payment } from '../interfaces/models';

const schema = new Schema<Payment>({
amount: { type: Number, required: true },
description: String,
festival: { type: Schema.Types.ObjectId, ref: 'Festival' },
festivalUser: { type: Schema.Types.ObjectId, ref: 'Festivaluser', required: true },
status: { type: String, enum: ["insufficientBalance", "insufficientAge", "accepted"], required: true }
})
amount: { type: Number, required: true },
description: String,
festival: { type: Schema.Types.ObjectId, ref: 'Festival' },
festivalUser: { type: Schema.Types.ObjectId, ref: 'Festivaluser', required: true },
status: { type: String, enum: ['insufficientBalance', 'insufficientAge', 'accepted'], required: true },
});

const PaymentModel = model<Payment>('Payment', schema);

const createPayment = async (transactionObj: any) => {
return PaymentModel.create(transactionObj)
}
const createPayment = async (transactionObj: any) => PaymentModel.create(transactionObj);

export {
createPayment
}
createPayment,
};
24 changes: 10 additions & 14 deletions src/models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,22 @@ const schema = new Schema<User>({
birthdate: { type: Date, required: true },
email: { type: String, required: true },
phoneNumber: { type: String, required: false },
status: { type: String, enum: ['unverified', 'verified'], required: true, default: 'unverified' },
status: {
type: String, enum: ['unverified', 'verified'], required: true, default: 'unverified',
},
gender: { type: Boolean, required: true },
});

const UserModel = model<User>('User', schema);

const getUserById = async (id: string) => {
return UserModel.findById(id).exec();
};
const getUserById = async (id: string) => UserModel.findById(id).exec();

const getAllUsers = async () => {
return UserModel.find();
}
const getAllUsers = async () => UserModel.find();

const createUser = async (userObj: any) => {
return UserModel.create(userObj)
};
const createUser = async (userObj: any) => UserModel.create(userObj);

const updateUserById = async (id: String, userObj: any) => {
return UserModel.findByIdAndUpdate(id, userObj, { new: true })
}
const updateUserById = async (id: String, userObj: any) => UserModel.findByIdAndUpdate(id, userObj, { new: true });

export { getUserById, getAllUsers, createUser, updateUserById };
export {
getUserById, getAllUsers, createUser, updateUserById,
};
69 changes: 69 additions & 0 deletions src/routes/festival-user.route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import express from 'express';
import { body, ValidationError, validationResult } from 'express-validator';
import { createFestivaluser, getFestivalUserById } from '../models/FestivalUser';
import { GetUserByIdRequest, GetUserByIdResponse, RegisterUserResponse } from '../interfaces/endpoints';
import { FestivalUser } from '../interfaces/models';

const router = express.Router();

router.get('/:id', async (req: express.Request & { params: GetUserByIdRequest }, res: express.Response) => {
const userId: string = req.params.id;

let resObj: GetUserByIdResponse = {
status: 404,
data: null,
message: 'Not Found.',
};

const user = await getFestivalUserById(userId);
if (user) {
resObj = {
status: 200,
data: user as any, // todo set type
message: 'Success',
};
return res.json(resObj);
}

return res.json(resObj);
});

router.post(
'/',
body('festivalId').isString().isLength({ min: 2 }),
body('userId').isString().isLength({ min: 2 }),
async (req: express.Request, res: express.Response) => {
// const { firstName, lastName, gender, birthdate, email, phoneNumber } = req.body;

let resObj: RegisterUserResponse = {
status: 404,
data: null,
message: 'Not implemented yet.',
};

const errors = validationResult(req);
if (!errors.isEmpty()) {
resObj = {
status: 400,
data: null,
message: 'Bad Request',
errors: errors.array().map((error: ValidationError) => ({
code: 400,
message: `${error.param}: ${error.msg}`,
})),
};
return res.status(400).json(resObj);
}

return res.json({
status: 201,
data: (await createFestivaluser({
userId: req.body.userId,
festivalId: req.body.festivalId,
})) as FestivalUser,
message: 'Created',
});
},
);

export default router;
129 changes: 129 additions & 0 deletions src/routes/festivals.route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import express from 'express';
import { body, ValidationError, validationResult } from 'express-validator';
import { Festival } from '../interfaces/models';
import {
CreateFestivalResponse,
GetAllFestivalsResponse,
GetFestivalByIdRequest,
GetFestivalByIdResponse,
UpdateFestivalResponse,
} from '../interfaces/endpoints';
import {
createFestival, getAllFestivals, getFestivalById, updateFestivalByID,
} from '../models/Festival';

const router = express.Router();

router.get('/', async (req: express.Request, res: express.Response) => {
const festivals = await getAllFestivals();
const resObj: GetAllFestivalsResponse = {
status: 200,
data: festivals,
message: 'Success',
};
return res.json(resObj);
});

router.get('/:id', async (req: express.Request & { params: GetFestivalByIdRequest }, res: express.Response) => {
const festivalId: string = req.params.id;

let resObj: GetFestivalByIdResponse = {
status: 404,
data: null,
message: 'Not implemented yet.',
};

const festival = await getFestivalById(festivalId);
if (festival) {
resObj = {
status: 200,
data: festival,
message: 'Success',
};
return res.json(resObj);
}

return res.json(resObj);
});

router.post(
'/',
body('name').isString().isLength({ min: 2 }),
body('description').isString().isLength({ min: 2 }),
body('location').isString(),
async (req: express.Request, res: express.Response) => {
// const { firstName, lastName, gender, birthdate, email, phoneNumber } = req.body;

let resObj: CreateFestivalResponse = {
status: 404,
data: null,
message: 'Not Found.',
};

const errors = validationResult(req);
if (!errors.isEmpty()) {
resObj = {
status: 400,
data: null,
message: 'Bad Request',
errors: errors.array().map((error: ValidationError) => ({
code: 400,
message: `${error.param}: ${error.msg}`,
})),
};
return res.status(400).json(resObj);
}

return res.json({
status: 201,
data: (await createFestival({
name: req.body.name,
description: req.body.description,
location: req.body.location,
})) as Festival,
message: 'Created',
});
},
);

router.put(
'/:id',
body('name').isString().isLength({ min: 2 }),
body('description').isString().isLength({ min: 2 }),
body('location').isString(),
async (req: express.Request, res: express.Response) => {
const festivalId: string = req.params.id;

let resObj: UpdateFestivalResponse = {
status: 404,
data: null,
message: 'Not Found.',
};

const errors = validationResult(req);
if (!errors.isEmpty()) {
resObj = {
status: 400,
data: null,
message: 'Bad Request',
errors: errors.array().map((error: ValidationError) => ({
code: 400,
message: `${error.param}: ${error.msg} => ${error.value}`,
})),
};
return res.status(400).json(resObj);
}

return res.json({
status: 201,
data: (await updateFestivalByID(festivalId, {
name: req.body.name,
description: req.body.description,
location: req.body.location,
})) as Festival,
message: 'Updated',
});
},
);

export default router;
Loading

0 comments on commit e95c741

Please sign in to comment.