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 #348

Open
wants to merge 2 commits into
base: master
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: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Building an API using a Relational Database
# Building an API using a Relational Database.

## Topics

Expand Down
30 changes: 30 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const express = require('express');
const server = express();
const requireAll = require('require-all');
var _ = require('lodash');
server.use(express.json());

const helmet = require('helmet');
server.use(helmet());

/*
// endpoints here

const port = 3300;
server.listen(port, function() {
console.log(`\n=== Web API Listening on http://localhost:${port} ===\n`);
});
*/

// add your server code starting here
server.listen(3300, () => console.log('server running'));

process.setMaxListeners(0);

const controllers = requireAll(__dirname + '/src/endpoints');
_.each(controllers, (endpoints, controller) => {
_.each(endpoints, (definition, endpoint) => {
console.log(`${endpoint}: /api/${controller}${definition.url}`);
server[definition.type.toLowerCase()](`/api/${controller}${definition.url}`, definition.handler);
});
});
12 changes: 12 additions & 0 deletions knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = {
development: {
client: 'sqlite3',
connection: { filename: './src/lambda.sqlite3' },
useNullAsDefault: true,
migrations: {
directory: './src/migrations',
tableName: 'dbmigrations',
},
seeds: { directory: './src/seeds' },
},
};
Binary file added lambda.sqlite3
Binary file not shown.
15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"scripts": {
"server": "nodemon index.js"
},
"dependencies": {
"express": "^4.16.4",
"helmet": "^3.15.0",
"knex": "^0.16.3",
"require-all": "^3.0.0",
"sqlite3": "^4.0.6"
},
"devDependencies": {
"nodemon": "^1.18.9"
}
}
46 changes: 46 additions & 0 deletions src/db/cohort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const db = require('../dbConfig.js');
const mappers = require('./mappers');

module.exports = {
get: function(id) {
let query = db('cohorts as c');

if (id) {
query.where('c.id', id).first();

/*const promises = [query, this.getProjectActions(id)]; // [ projects, actions ]

return Promise.all(promises).then(function(results) {
let [project, actions] = results;
project.actions = actions;

return mappers.projectToBody(project);
});*/
}

return query/*.then(projects => {
return projects.map(project => mappers.projectToBody(project));
});*/
},/*
getProjectActions: function(projectId) {
return db('actions')
.where('project_id', projectId)
.then(actions => actions.map(action => mappers.actionToBody(action)));
},*/
insert: function(cohort) {
return db('cohorts')
.insert(cohort)
.then(([id]) => this.get(id));
},
update: function(id, changes) {
return db('cohorts')
.where('id', id)
.update(changes)
.then(count => (count > 0 ? this.get(id) : null));
},
remove: function(id) {
return db('cohorts')
.where('id', id)
.del();
},
};
37 changes: 37 additions & 0 deletions src/db/mappers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
module.exports = {
intToBoolean,
booleanToint,
projectToBody,
actionToBody,
};

function intToBoolean(int) {
return int === 1 ? true : false;
}

function booleanToint(bool) {
return bool === true ? 1 : 0;
}

function projectToBody(project) {
const result = {
...project,
completed: intToBoolean(project.completed),
};

if (project.actions) {
result.actions = project.actions.map(action => ({
...action,
completed: intToBoolean(action.completed),
}));
}

return result;
}

function actionToBody(action) {
return {
...action,
completed: intToBoolean(action.completed),
};
}
35 changes: 35 additions & 0 deletions src/db/student.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const db = require('../dbConfig.js');
const mappers = require('./mappers');

module.exports = {
get: function(id) {
let query = db('students');

if (id) {
return query
.where('id', id)
.first()/*
.then(action => mappers.actionToBody(action));*/
}

return query/*.then(actions => {
return actions.map(action => mappers.actionToBody(action));
});*/
},
insert: function(student) {
return db('students')
.insert(student)
.then(([id]) => this.get(id));
},
update: function(id, changes) {
return db('students')
.where('id', id)
.update(changes)
.then(count => (count > 0 ? this.get(id) : null));
},
remove: function(id) {
return db('students')
.where('id', id)
.del();
},
};
4 changes: 4 additions & 0 deletions src/dbConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const knex = require('knex');
const knexConfig = require('../knexfile.js');

module.exports = knex(knexConfig.development);
25 changes: 25 additions & 0 deletions src/endpoints/cohort/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const express = require('express');
const cohortDb = require('../../db/cohort.js');
const validators = require('../../validators/cohort/create.js');

module.exports = {
type: 'POST',
url: '/',
handler: (req, res) => {
const {name} = req.body;
let cohort = {
name: name,
}
const newKeys = Object.keys(cohort);
const validations = newKeys.map(key => validators[key](cohort));
Promise.all(validations).then(() => {
cohortDb.insert(cohort)
.then(id => {
res.status(201).json(id);
})
.catch(err => {
res.status(500).json({ error: "There was an error while saving the new cohort to the database." });
});
}).catch(err => res.status(err.statusCode || 500).json(err.stack));
}
}
30 changes: 30 additions & 0 deletions src/endpoints/cohort/delete.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const express = require('express');
const cohortDb = require('../../db/cohort.js');

module.exports = {
type: 'DELETE',
url: '/:id',
handler: (req, res) => {
cohortDb.get(req.params.id)
.then(cohort => {
if (cohort != undefined) {
cohortDb.remove(req.params.id)
.then(numRemoved => {
if(numRemoved === 1){
res.status(202).json({message: "Cohort successfully deleted."});
}else{
res.status(202).json({message: "Request accepted but no object deleted."});
}
})
.catch(err => {
res.status(500).json({ error: "The cohort could not be removed." });
});
}else{
res.status(404).json({ message: "The cohort with the specified ID does not exist." });
}
})
.catch(err => {
res.status(500).json({ error: "The cohort information could not be retrieved." });
})
}
}
17 changes: 17 additions & 0 deletions src/endpoints/cohort/list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const express = require('express');
const cohortDb = require('../../db/cohort.js');

module.exports = {
type: 'GET',
url: 's/',
handler: (req, res) => {
cohortDb.get()
.then(cohorts => {
res.status(200).json(cohorts);
})
.catch(err => {
console.log(err);
res.status(500).json({ error: "Could not retrieve cohorts." });
})
}
}
22 changes: 22 additions & 0 deletions src/endpoints/cohort/retrieve.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const express = require('express');
const cohortDb = require('../../db/cohort.js');

module.exports = {
type: 'GET',
url: '/:id',
handler: (req, res) => {
const { id } = req.params;
cohortDb.get(id)
.then(cohort => {
if(cohort != undefined){
res.status(200).json(cohort);
}else{
res.status(404).json({ error: "Cohort not found."});
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: "Could not retrieve cohort." });
});
}
}
31 changes: 31 additions & 0 deletions src/endpoints/cohort/update.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const express = require('express');
const cohortDb = require('../../db/cohort.js');
const validators = require('../../validators/cohort/update.js');

module.exports = {
type: 'PUT',
url: '/:id',
handler: (req, res) => {
const {name} = req.body;
const {id} = req.params;
let modifiedCohort = {
name: name,
}
const changedKeys = Object.keys(modifiedCohort);
const validations = changedKeys.map(key => validators[key](modifiedCohort));
Promise.all(validations).then(() => {
cohortDb.update(id, modifiedCohort)
.then(response => {
if(response === null){
res.status(404).json({message: "Cohort not found."});
}else{
res.status(200).json(response);
}
})
.catch(err => {
res.status(500).json({ error: "The cohort information could not be retrieved." });
})
}).catch(err => res.status(err.statusCode || 500).json(err.stack));

}
}
43 changes: 43 additions & 0 deletions src/endpoints/student/create.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const express = require('express');
const studentDb = require('../../db/student.js');
const cohortDb = require('../../db/cohort.js');
const validators = require('../../validators/student/create.js');

module.exports = {
type: 'POST',
url: '/',
handler: (req, res) => {
console.log(req.body);
const {cohort_id, name} = req.body;
let newStudent = {
cohort_id: cohort_id,
name: name,
}
console.log(newStudent);
const newKeys = Object.keys(newStudent);
console.log(newKeys);
const validations = newKeys.map(key => validators[key](newStudent));
Promise.all(validations).then(() => {
cohortDb.get(cohort_id)
.then(cohort => {
if(cohort != undefined){
studentDb.insert(newStudent)
.then(id => {
res.status(201).json(id);
})
.catch(err => {
res.status(500).json({ error: "There was an error while saving the student to the database." });
});
}else{
res.status(400).json({ error: "Please provide valid cohort ID." });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: "The cohort information could not be retrieved." });
})
}).catch(err => {
res.status(err.statusCode || 500).json(err.message);
});
}
}
Loading