Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
8463645-6003CEM-Backend-Resit-Deferral/routes/users.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
70 lines (60 sloc)
1.86 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Router = require('koa-router'); | |
const bodyParser = require('koa-bodyparser'); | |
const model = require('../models/users'); | |
const router = Router({prefix: '/api/v1/users'}); | |
router.get('/', getAll); | |
router.post('/', bodyParser(), createUser); | |
router.get('/:id([0-9]{1,})', getById); | |
router.put('/:id([0-9]{1,})', bodyParser(), updateUser); | |
router.del('/:id([0-9]{1,})', deleteUser); | |
async function getAll(ctx) { | |
const result = await model.getAll(); | |
if (result.length) { | |
ctx.body = result; | |
} | |
} | |
async function getById(ctx) { | |
const id = ctx.params.id; | |
const result = await model.getById(id); | |
if (result.length) { | |
const user = result[0] | |
ctx.body = user; | |
} | |
} | |
//get a single user by the (unique) username | |
exports.findByUsername = async function getByUsername(username) { | |
const query = "SELECT * FROM users WHERE username = ?;"; | |
const user = await db.run_query(query, username); | |
return user; | |
} | |
async function createUser(ctx) { | |
const body = ctx.request.body; | |
const result = await model.add(body); | |
if (result.affectedRows) { | |
const id = result.insertId; | |
ctx.status = 201; | |
ctx.body = {ID: id, created: true, link: `${ctx.request.path}/${id}`}; | |
} | |
} | |
async function updateUser(ctx) { | |
const id = ctx.params.id; | |
let result = await model.getById(id); // check it exists | |
if (result.length) { | |
let user = result[0]; | |
// exclude fields that should not be updated | |
const {ID, dateRegistered, ...body} = ctx.request.body; | |
Object.assign(user, body); // overwrite updatable fields with body data | |
result = await model.update(user); | |
if (result.affectedRows) { | |
ctx.body = {ID: id, updated: true, link: ctx.request.path}; | |
} | |
} | |
} | |
async function deleteUser(ctx) { | |
const id = ctx.params.id; | |
const result = await model.delById(id); | |
if (result.affectedRows) { | |
ctx.body = {ID: id, deleted: true} | |
} | |
} | |
module.exports = router; |