Skip to content

Dwaine matthew #32

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 2 commits into
base: main
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
62 changes: 62 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/
**/node_modules

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# next.js build output
.next

# enviroment variable
.env
151 changes: 151 additions & 0 deletions User/post-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
const express = require("express")
const db = require("../data/db")

const router = express.Router()

// GET ALL POSTS
router.get("/posts", (req, res) => {
console.log(req.query)
db.find()
.then((posts) => {
res.status(200).json(posts)
})
.catch((error) => {
console.log(error)
res.status(500).json({
message: "Error retrieving the posts",
})
})
})

// GET SPECIFIC POST
router.get("/posts/:id", (req, res) => {
db.findById(req.params.id)
.then((post) => {
if (post) {
res.json(post)
} else {
res.status(404).json({
message: "The post with the specified ID does not exist."
})
}
})
.catch((error) => {
console.log(error)
res.status(500).json({
error: "You screwed up"
})
})
})

// CREATE NEW POST
router.post("/posts", (req, res) => {
if (!req.body.title || !req.body.contents) {
return res.status(400).json({
errorMessage: "Please provide title and contents for the post."
})
}

db.insert(req.body)
.then((post) => {
res.status(201).json(post)
})
.catch((error) => {
console.log(error)
res.status(500).json({
error: "There was an error while saving the post to the database."
})
})
})

// GET COMMENTS FOR POST BY ID
router.get("/posts/:id/comments", (req, res) => {
db.findPostComments(req.params.id)
.then((comments) => {
if (comments) {
res.json(comments)
} else {
res.status(404).json({
errorMessage: "Post not found."
})
}
})
.catch((error) => {
console.log(error)
res.status(500).json({
error: "Error retrieving the post",
})
})
})

// CREATE NEW COMMENT FOR POST BY ID
router.post("/posts/:id/comments", (req, res) => {

if (!req.body.text) {
return res.status(400).json({
message: "Need a text in the body fam",
})
}

db.insertComment({ text: req.body.text, post_id: req.params.id })
.then((comment) => {
res.status(201).json({
post_id: req.params.id,
text: req.body.text
})
})
.catch((err) => {
console.log(err)
res.status(500).json({
message: "Something ain't right. We didn't add the comment.",
})
})
})

// DELETE POST BY ID
router.delete("/posts/:id", (req, res) => {
db.remove(req.params.id)
.then((count) => {
if (count > 0) {
res.status(200).json({
message: "The post has been removed",
})
} else {
res.status(404).json({
message: "The post could not be found",
})
}
})
})

// UPDATE POST BY ID
router.put("/posts/:id", (req, res) => {
if (!req.body) {
return res.status(400)({
message: "Missing title or contents"
})
}

db.update(req.params.id, req.body)
.then((post) => {
if (post) {
res.status(201).json({
id: req.params.id,
title: req.body.title,
contents: req.body.contents,
})
} else {
res.status(404).json({
message: "The post could not be found",
})
}
})
.catch((error) => {
console.log(error)
res.status(500).json({
message: "Error updating the post",
})
})
})

module.exports = router
60 changes: 60 additions & 0 deletions data/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const knex = require('knex');
const knexConfig = require('../knexfile.js');
const db = knex(knexConfig.development);

module.exports = {
find,
findById,
insert,
update,
remove,
findPostComments,
findCommentById,
insertComment,
};

function find() {
return db('posts');
}

function findById(id) {
return db('posts').where({ id: Number(id) });
}

function insert(post) {
return db('posts')
.insert(post, 'id')
.then(ids => ({ id: ids[0] }));
}

function update(id, post) {
return db('posts')
.where('id', Number(id))
.update(post);
}

function remove(id) {
return db('posts')
.where('id', Number(id))
.del();
}

function findPostComments(postId) {
return db('comments')
.join('posts', 'posts.id', 'post_id')
.select('comments.*', 'title as post')
.where('post_id', postId);
}

function findCommentById(id) {
return db('comments')
.join('posts', 'posts.id', 'post_id')
.select('comments.*', 'title as post')
.where('comments.id', id);
}

function insertComment(comment) {
return db('comments')
.insert(comment)
.then(ids => ({ id: ids[0] }));
}
Binary file added data/lambda.db3
Binary file not shown.
14 changes: 14 additions & 0 deletions data/migrations/20180401213248_add_posts_table.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
exports.up = function(knex) {
return knex.schema.createTable('posts', function(posts) {
posts.increments();

posts.string('title', 1024).notNullable();
posts.text('contents').notNullable();

posts.timestamps(true, true);
});
};

exports.down = function(knex) {
return knex.schema.dropTableIfExists('posts');
};
22 changes: 22 additions & 0 deletions data/migrations/20190509175531_add_comments_table.js.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
exports.up = function(knex) {
return knex.schema.createTable('comments', tbl => {
tbl.increments();

tbl.string('text').notNullable();

tbl
.integer('post_id')
.unsigned()
.notNullable()
.references('id')
.inTable('posts')
.onDelete('CASCADE')
.onUpdate('CASCADE');

tbl.timestamps(true, true);
});
};

exports.down = function(knex) {
return knex.schema.dropTableIfExists('comments');
};
52 changes: 52 additions & 0 deletions data/seeds/01-posts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
exports.seed = function(knex, Promise) {
return knex('posts')
.truncate()
.then(function() {
return knex('posts').insert([
{
title:
'I wish the ring had never come to me. I wish none of this had happened.',
contents: 'Guess who said this',
},
{
title: 'I think we should get off the road. Get off the road! Quick!',
contents: 'Guess who said this',
},
{
title:
"I made a promise, Mr Frodo. A promise. \"Don't you leave him Samwise Gamgee.\" And I don't mean to. I don't mean to.",
contents: 'Guess who said this',
},
{
title:
" N-nothing important. That is, I heard a great deal about a ring, a Dark Lord, and something about the end of the world, but... Please, Mr. Gandalf, sir, don't hurt me. Don't turn me into anything... unnatural.",
contents: 'Guess who said this',
},
{
title:
'You need people of intelligence on this sort of mission...quest...thing.',
contents: 'Guess who said this',
},
{
title:
'All you have to do is decide what to do with the time that is given to you.',
contents: 'Guess who said this',
},
{
title:
'Do not be so quick to deal out death and judgement. Even the very wise do not see all ends.',
contents: 'Guess who said this',
},
{
title:
' Fool of a Took! Throw yourself in next time and rid us of your stupidity!',
contents: 'Guess who said this',
},
{
title:
'I will be dead before I see the ring in the hands of an elf! Never trust an elf!',
contents: 'Guess who said this',
},
]);
});
};
20 changes: 20 additions & 0 deletions data/seeds/02-comments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

exports.seed = function(knex, Promise) {
return knex('comments').truncate()
.then(function () {
return knex('comments').insert([
{text: "Let your workings remain a mystery. Just show people the results.", post_id: 1},
{text: "True mastery can be gained by letting things go their own way. It can't be gained by interfering.", post_id: 1 },
{text: "Not-knowing is true knowledge. Presuming to know is a disease.", post_id: 2 },
{text: "Success or failure: which is more destructive?", post_id: 4 },
{text: "When two great forces oppose each other the victory will go to the one that knows how to yield.", post_id: 4 },
{text: "Things arise and she let's them come; things disappear and she let's them go.", post_id: 4 },
{text: "A good travel has no fixed plans and is not intent upon arriving. A good artist lets his intuition lead him where ever it wants.", post_id: 5 },
{text: "When you look for it, there is nothing to see. When you listen for it, there is nothing to hear. When you use it, it is inexhaustible.", post_id: 7 },
{text: "She acts without expectation, succeeds without taking credit and doesn't think she is better than anyone else.", post_id: 7 },
{text: "Act without doing; work without effort.", post_id: 7 },
{text: "Do you have the patience to wait until your mud settles and the water is clear? Can you remain unmoving until the right action arises by itself?", post_id: 8 },
{text: "He who tries to shine dims his own light. He who defines himself can't know who he really is. He who clings to his work will do nothing that endures. Just do your job, then let go.", post_id: 8 }
]);
});
};
Loading