Skip to content

Rigo #34

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

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open

Rigo #34

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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules

#ENV
.env
34 changes: 34 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const express = require("express");
const router = express.Router();
const helmet = require("helmet");
const cors = require("cors");

//server
const server = express();

//import routers
const welcomeRouter = require("../welcome/welcome-router");
const usersRouter = require("../users/users-router");
const commentsRouter = require("../comments/comments-router");

//Global middleware
server.use(helmet());
server.use(cors());
server.use(express.json());

//Server endpoints --------->
server.use("/", welcomeRouter);
// --> /api/users
server.use("/api/users", usersRouter);
// --> /api/comments
server.use("/api/comments", commentsRouter);

//middleware for CATCH ERROR on all endpoints of /api/messages
server.use((err, req, res, next) => {
console.log(err);
res.status(500).json({
message: "500 error: Something went wrong",
});
});

module.exports = server;
24 changes: 24 additions & 0 deletions comments/comments-middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const Comments = require("./comments-model");

module.exports = {
checkCommentID,
};

//check for ID
function checkCommentID() {
return (req, res, next) => {
const { id } = req.params;
Comments.getById(id)
.then((commentID) => {
if (commentID) {
req.commentID = commentID;
next();
} else {
res
.status(404)
.json({ error: `can't find comment by user of id # ${id}` });
}
})
.catch((err) => next(err));
};
}
48 changes: 48 additions & 0 deletions comments/comments-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const db = require("../database/dbConfig");

module.exports = {
getComments,
getById,
postComment,
deleteComment,
updateComment,
};

//USERS C.R.U.D
//GET /api/comments
function getComments() {
return db("comments").select("comments.*");
}

//GET /api/comments/:id
function getById(id) {
return db("comments").where({ id }).first();
}

//POST /api/comments
function postComment(commentBody) {
//req.body on router
return db("comments")
.insert(commentBody, "id")
.then((ids) => {
//ids makes sure we targe the selected ID posts only
console.log(ids);
return db("comments").where({ id: ids }).first();
});
}

//DELETE /api/comments/:id
function deleteComment(id) {
return db("comments").where({ id }).del();
}

//UPDATE PUT /api/comments/:id
function updateComment(id, changes) {
return db("comments")
.update(changes)
.where({ id })
.then((ids) => {
console.log("ids---update--->", ids);
return db("comments").where({ id: id }).first();
});
}
60 changes: 60 additions & 0 deletions comments/comments-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const express = require("express");
const router = express.Router();
const Comments = require("./comments-model");
const { checkCommentID } = require("../comments/comments-middleware");

//GET /api/comments
router.get("/", (req, res, next) => {
Comments.getComments()
.then((comment) => {
comment
? res.status(200).json(comment)
: res.status(404).json({ message: `no comments found..` });
})
.catch((err) => next(err));
});

//GET /api/comments/:id
router.get("/:id", checkCommentID(), (req, res, next) => {
res.status(200).json(req.commentID);
});

//POST /api/comments
router.post("/", (req, res, next) => {
const body = req.body;
Comments.postComment(body)
.then((comment) => {
comment
? res.status(201).json(comment)
: res.status(404).json({ error: `can't post that user of ${body}` });
})
.catch((err) => next(err));
});

//DELETE /api/comments/:id
router.delete("/:id", checkCommentID(), (req, res, next) => {
const { id } = req.params;
Comments.deleteComment(id)
.then((post) => {
console.log("post---->", post);
post
? res.status(200).json({ deleted: post })
: res.status(404).json({ error: `can't delete user by ${id}` });
})
.catch((err) => next(err));
});

//UPDATE /api/comments/:id
router.put("/:id", (req, res, next) => {
const commentBody = req.body;
const { id } = req.params;

Comments.updateComment(id, commentBody)
.then((comment) => {
res.status(200).json(comment);
console.log("comment update--->", comment);
})
.catch((err) => next(err));
});

module.exports = router;
4 changes: 4 additions & 0 deletions database/dbConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const knex = require("knex");
const config = require("../knexfile");
const environment = process.env.NODE_ENV || "development";
module.exports = knex(config[environment]);
25 changes: 25 additions & 0 deletions database/migrations/20210121220708_create-users-table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
exports.up = function (knex) {
return knex.schema
.createTable("users", (tbl) => {
tbl.increments("id");
tbl.string("name", 128).notNull().unique();
tbl.integer("age", 128).notNull();
tbl.string("location", 128).notNull();
})
.createTable("comments", function (tbl) {
tbl.increments("id");
tbl.text("comment").notNull();
tbl
.integer("user_id")
.unsigned()
.notNull()
.references("id")
.inTable("users")
.onDelete("CASCADE")
.onUpdate("CASCADE");
});
};

exports.down = function (knex) {
return knex.schema.dropTableIfExists("comments").dropTableIfExists("users");
};
10 changes: 10 additions & 0 deletions database/seeds/00-cleanup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const cleaner = require("knex-cleaner");

exports.seed = function (knex) {
return cleaner.clean(knex, {
mode: "truncate", // resets ids
// don't empty migration tables
//no need to use truncate on seed users
ignoreTables: ["knex_migrations", "knex_migrations_lock"],
});
};
56 changes: 56 additions & 0 deletions database/seeds/01-users.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const faker = require("faker");

exports.seed = function (knex) {
return knex("users").insert([
{
name: faker.name.findName(),
age: faker.datatype.number(),
location: faker.address.city(),
},
{
name: faker.name.findName(),
age: faker.datatype.number(),
location: faker.address.city(),
},
{
name: faker.name.findName(),
age: faker.datatype.number(),
location: faker.address.city(),
},
{
name: faker.name.findName(),
age: faker.datatype.number(),
location: faker.address.city(),
},
{
name: faker.name.findName(),
age: faker.datatype.number(),
location: faker.address.city(),
},
// {
// name: faker.name.findName(),
// age: faker.datatype.number(),
// location: faker.address.city(),
// },
// {
// name: faker.name.findName(),
// age: faker.datatype.number(),
// location: faker.address.city(),
// },
// {
// name: faker.name.findName(),
// age: faker.datatype.number(),
// location: faker.address.city(),
// },
// {
// name: faker.name.findName(),
// age: faker.datatype.number(),
// location: faker.address.city(),
// },
// {
// name: faker.name.findName(),
// age: faker.datatype.number(),
// location: faker.address.city(),
// },
]);
};
28 changes: 28 additions & 0 deletions database/seeds/02-comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
exports.seed = function (knex, Promise) {
return knex("comments").insert([
{
user_id: 1,
comment: "this is comment for first user",
},
{
user_id: 1,
comment: "this is the 3rd comment for first user",
},
{
user_id: 2,
comment: "this is comment for second user",
},
{
user_id: 3,
comment: "this is comment for third user",
},
{
user_id: 4,
comment: "this is comment for fourth user",
},
{
user_id: 5,
comment: "this is comment for fifth user",
},
]);
};
Binary file added database/users.db3
Binary file not shown.
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const server = require("./api/server");
require("dotenv").config();

//env 5000
const port = process.env.PORT || 4000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
56 changes: 56 additions & 0 deletions knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Update with your config settings.
require("dotenv").config();

module.exports = {
development: {
client: "sqlite3",
connection: {
filename: "./database/users.db3",
},
useNullAsDefault: true,
migrations: {
directory: "./database/migrations",
},
seeds: {
directory: "./database/seeds",
},
pool: {
// for foreign keys only
afterCreate: (conn, done) => {
// runs after a connection is made to the sqlite engine
conn.run("PRAGMA foreign_keys = ON", done); // turn on FK enforcement
},
},
},

staging: {
client: "postgresql",
connection: {
database: "my_db",
user: "username",
password: "password",
},
pool: {
min: 2,
max: 10,
},
migrations: {
tableName: "knex_migrations",
},
},

production: {
client: "pg",
connection: process.env.DATABASE_URL,
migrations: {
directory: "./database/migrations",
tableName: "knex_migrations",
},
seeds: {
directory: "./database/seeds",
},
pool: { min: 2, max: 10 },
},
};

// require("./database/")
Loading