Skip to content

Commit

Permalink
- delete user route
Browse files Browse the repository at this point in the history
- update user route
  • Loading branch information
asad-mlbd committed Jun 6, 2020
1 parent acec904 commit 0162ae0
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 4 deletions.
43 changes: 42 additions & 1 deletion repositories/user.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,45 @@ const createUser = async (user: { name: string; email: string }) => {
return users[0];
};

export { getUsers, getUserById, createUser };
/**
* Update user
*/
const updateUser = async (
id: number,
user: { name: string; email: string },
) => {
const { name, email } = user;
await db.query(
`
UPDATE users SET
name = ?,
email = ?,
updated_at = DEFAULT
WHERE id = ?;
`,
[name, email, id],
);
const users = await db.query(
`SELECT * from users where id = ? limit 0, 1`,
[id],
);

return users[0];
};

/**
* Delete user
*/
const deleteUser = async (
id: number,
) => {
await db.query(
`
DELETE FROM users
WHERE id = ?;
`,
[id],
);
};

export { getUsers, getUserById, createUser, updateUser, deleteUser };
4 changes: 3 additions & 1 deletion routes/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ router.get("", (ctx: Context) => {
router
.get("/users", userRoutes.getUsers)
.get("/users/:id", userRoutes.getUserById)
.post("/users", userRoutes.createUser);
.post("/users", userRoutes.createUser)
.put("/users/:id", userRoutes.updateUser)
.delete("/users/:id", userRoutes.deleteUser);

export { router };
22 changes: 20 additions & 2 deletions routes/user.routes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Context, helpers } from "https://deno.land/x/[email protected]/mod.ts";
import {
Context,
helpers,
Status,
} from "https://deno.land/x/[email protected]/mod.ts";
import * as userRepo from "./../repositories/user.repository.ts";

const getUsers = async (ctx: Context) => {
Expand All @@ -19,4 +23,18 @@ const createUser = async (ctx: Context) => {
ctx.response.body = user;
};

export { getUsers, getUserById, createUser };
const updateUser = async (ctx: Context) => {
const { id } = helpers.getQuery(ctx, { mergeParams: true });
const request = ctx.request;
const userData = (await request.body()).value;
const user = await userRepo.updateUser(+id, userData);
ctx.response.body = user;
};

const deleteUser = async (ctx: Context) => {
const { id } = helpers.getQuery(ctx, { mergeParams: true });
await userRepo.deleteUser(+id);
ctx.response.status = Status.NoContent;
};

export { getUsers, getUserById, createUser, updateUser, deleteUser };

0 comments on commit 0162ae0

Please sign in to comment.