Skip to content

Commit

Permalink
add technonatura branch
Browse files Browse the repository at this point in the history
  • Loading branch information
Aldhanekaa committed Aug 9, 2021
1 parent 791a943 commit 3a1b620
Show file tree
Hide file tree
Showing 11 changed files with 256 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/controllers/auth/admin/acceptUsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,31 @@ AuthRouter.post('/acceptusers', VerifyAuthToken, async (req, res) => {
try {
// console.log(usersId, userId, 'userId');
const verifiedUser = await User.findById(userId);
console.log(req.query);
if (req.query.teacher && verifiedUser) {

// @ts-ignore
if (verifiedUser?.roleInTechnoNatura.teacher) {
if (!verifiedUser.roles.includes('teacher')) {
verifiedUser.roles.push('teacher');
}
await verifiedUser.updateOne({
isAccountVerified: true,
roles: [...verifiedUser.roles],
$set: {
// @ts-ignore
roleInTechnoNatura: {
...verifiedUser.roleInTechnoNatura,
isVerified: true,
},
},
});
// @ts-ignore
} else if (verifiedUser?.roleInTechnoNatura.staff) {
if (!verifiedUser.roles.includes('staff')) {
verifiedUser.roles.push('staff');
}
await verifiedUser.updateOne({
isAccountVerified: true,
roles: [...verifiedUser.roles],
$set: {
// @ts-ignore
roleInTechnoNatura: {
Expand Down
5 changes: 5 additions & 0 deletions src/controllers/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ AuthRouter.post('/signup', async (req, res) => {
gender,
birthDate,
staffRole,
branch,
}: {
email: string;
password: string;
Expand All @@ -115,6 +116,7 @@ AuthRouter.post('/signup', async (req, res) => {
staffRole: string;

birthDate: string;
branch: string;
} = req.body;

// console.log(req.body);
Expand Down Expand Up @@ -162,18 +164,21 @@ AuthRouter.post('/signup', async (req, res) => {

// @ts-ignore
startPeriod,
branch,
};
} else if (roleInTechnoNatura === 'mentor') {
user.roleInTechnoNatura = {
teacher: true,
grade: gradeInNumber,
isVerified: false,
branch,
};
} else if (roleInTechnoNatura === 'staff') {
user.roleInTechnoNatura = {
staff: true,
role: staffRole,
isVerified: false,
branch,
};
}

Expand Down
57 changes: 57 additions & 0 deletions src/controllers/branch/handleErrors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* =================== MTS TECHNONATURA SERVER =================
*
* This API Script under MIT LICENSE
* What is this for ? This is REST API for MTS Technonatura arduino database, user make app and saved the app to db.
*
* (c) 2021 by MTS-Technonatura, made with 💖 by Aldhan
* =============================================================
*/

interface Errors {
desc: string;
name: string;
}

// handle errors
async function handleErrors(err: {
message: string;
code: number;
_message: string;
keyValue: {
name?: string;
title?: string;
};
}) {
// @ts-ignore
let errors: Errors = {};

if (err.message == 'Only Letters and Numbers are allowed') {
errors.name = err.message;
}

// duplicate username error
if (err.code === 11000 && err.keyValue.name) {
errors.name = 'that name is already registered';
}

// validation errors
if (
err._message &&
err._message.includes('TechnoNaturaBranch validation failed')
) {
// @ts-ignore
Object.values(err.errors).forEach(({ properties }) => {
// console.log(val);
// console.log(properties);
if (properties.message) {
// @ts-ignore
errors[properties.path] = properties.message;
}
});
}

return errors;
}

export default handleErrors;
32 changes: 32 additions & 0 deletions src/controllers/public/branch.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* =================== TECHNONATURA SERVER =================
*
* This API Script under MIT LICENSE
*
* (c) 2021 by Aldhan
* =============================================================
*/

import * as express from 'express';

import TechnoNaturaBranch from '../../models/TechnoNatura-Branch/TechnoNatura-Branch.model';

const TechnoNaturaBranchRouter = express.Router();

TechnoNaturaBranchRouter.get('/branches', async (req, res) => {
try {
const branches = await TechnoNaturaBranch.find();
res.json({
message: 'Success fetching branches!',
status: 'success',
branches,
});
} catch (err) {
res.json({
message: 'Error when fetching TechnoNatura Branches',
status: 'error',
});
}
});

export default TechnoNaturaBranchRouter;
65 changes: 65 additions & 0 deletions src/models/TechnoNatura-Branch/TechnoNatura-Branch.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { Schema, Model, Document, model, Types, Query, Error } from 'mongoose';

import { TechnonaturaBranchI } from './index';

export { TechnonaturaBranchI };

export interface TechnonaturaBranchBaseDocument
extends TechnonaturaBranchI,
Document {}

// Export this for strong typing
export interface TechnonaturaBranchDocument
extends TechnonaturaBranchBaseDocument {}

// For model
export interface TechnonaturaBranchModel
extends Model<TechnonaturaBranchBaseDocument> {}

const userSchema = new Schema<
TechnonaturaBranchDocument,
TechnonaturaBranchModel
>({
title: {
type: String,
required: [true, 'Please enter your name'],
minlength: [4, 'Minimum name length is 4 characters'],
},
active: {
type: Boolean,
default: false,
},
name: {
type: String,
lowercase: true,
unique: true,
required: [true, 'username cannot be blank'],
validate: [
validateTechnonaturaBranchname,
'Only Letters and Numbers are allowed',
],
},
});

function validateTechnonaturaBranchname(str: string) {
if (!str.match(/^[A-Za-z0-9_-]*$/)) {
return false;
}

return true;
}

// fire a function before doc saved to db
// userSchema.pre('save', async function(next) {
// // console.log('hello');
// const salt = await bcrypt.genSalt();
// this.password = await bcrypt.hash(this.password, salt);
// // this.email = await EncryptEmail(this.email);

// next();
// });

export default model<TechnonaturaBranchDocument, TechnonaturaBranchModel>(
'TechnoNaturaBranch',
userSchema,
);
5 changes: 5 additions & 0 deletions src/models/TechnoNatura-Branch/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export interface TechnonaturaBranchI {
title: string;
name: string;
active: boolean;
}
16 changes: 16 additions & 0 deletions src/models/User/User.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,16 +151,28 @@ const userSchema = new Schema<UserDocument, UserModel>({
teacher: Boolean,
grade: Number,
isVerified: Boolean,
branch: {
type: String,
required: [true, 'technonatura branch cannot be blank'],
},
},
{
staff: Boolean,
role: String,
isVerified: Boolean,
branch: {
type: String,
required: [true, 'technonatura branch cannot be blank'],
},
},
{
student: Boolean,
grade: Number,
startPeriod: Number,
branch: {
type: String,
required: [true, 'technonatura branch cannot be blank'],
},
},
{
alumni: Boolean,
Expand All @@ -171,6 +183,10 @@ const userSchema = new Schema<UserDocument, UserModel>({
enum: ['mi', 'mts', 'ma'],
},
startPeriod: Number,
branch: {
type: String,
required: [true, 'technonatura branch cannot be blank'],
},
},
],
},
Expand Down
5 changes: 5 additions & 0 deletions src/models/User/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,22 @@ export interface StaffRoleInTechnoNatura {
staff: boolean;
role: string;
isVerified: boolean;

branch: string;
}

export interface StudentRoleInTechnoNatura {
student: boolean;
grade: GradeInNumber;
startPeriod: number;

branch: string;
}

export type AlumniRoleInTechnoNatura = Array<{
grade: Grade;
startPeriod: number;
branch: string;
}>;

export interface UserInterface {
Expand Down
3 changes: 3 additions & 0 deletions src/routes/any.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ import BlogPost from '../models/Blog/BlogPost.model';

import User from '../models/User/User.model';

import TechnoNaturaBranchController from '../controllers/public/branch.controller';

const AnyRouter = express.Router();

AnyRouter.use('/', TechnoNaturaBranchController);
AnyRouter.get('/allData', async (req, res) => {
const allUsers = User.count();
const verifiedUsers = User.find({ isAccountVerified: true }).count();
Expand Down
41 changes: 41 additions & 0 deletions src/routes/branch.route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* =================== TECHNONATURA SERVER =================
*
* This API Script under MIT LICENSE
* What is this for ? This is REST API for MTS Technonatura arduino database, user make app and saved the app to db.
*
* (c) 2021 by Aldhan
* =============================================================
*/

import * as express from 'express';

import TechnoNaturaBranch from '../models/TechnoNatura-Branch/TechnoNatura-Branch.model';
import TechnoNaturaBranchHandleErrors from '../controllers/branch/handleErrors';

const TechnoNaturaBranchRouter = express.Router();

TechnoNaturaBranchRouter.post('/add', async (req, res) => {
const { title, name } = req.body;

try {
const branch = new TechnoNaturaBranch({ title, name });
await branch.save();
res.json({
message: 'Success add branch!',
status: 'success',
branch,
});
return;
} catch (err) {
const errors = await TechnoNaturaBranchHandleErrors(err);
res.json({
message: 'Error when fetching TechnoNatura Branches',
status: 'error',
errors: errors,
});
return;
}
});

export default TechnoNaturaBranchRouter;
4 changes: 4 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ import ArduinoRouter from './routes/arduino.route';
import StoryRouter from './routes/story.route';
import SubscriptionRouter from './routes/subsciption.router';
import AnythingRouter from './routes/any.route';

import BranchRouter from './routes/branch.route';

import { corsOptions } from './controllers/cors';

// import Socketmain from './socket/index';
Expand Down Expand Up @@ -81,6 +84,7 @@ app.use('/auth', cors(corsOptions), AuthRouter);
app.use('/contact', cors(corsOptions), ContactRouter);
app.use('/arduino', ArduinoRouter);
app.use('/story', cors(corsOptions), StoryRouter);
app.use('/branch', cors(corsOptions), BranchRouter);
app.use('/', SubscriptionRouter);
app.use(
'/api',
Expand Down

0 comments on commit 3a1b620

Please sign in to comment.