Skip to content

Commit

Permalink
Merge pull request #30 from fac19/getexampleid
Browse files Browse the repository at this point in the history
Getexampleid
  • Loading branch information
Roger-Heathcote authored Apr 16, 2020
2 parents 8c04525 + 19bda6d commit 464b5aa
Show file tree
Hide file tree
Showing 6 changed files with 199 additions and 20 deletions.
18 changes: 16 additions & 2 deletions handlers/examples.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ function getAllExamples(req, res, next) {
.getAllExamples()
.then((example) => res.send(example))
.catch(next);
//You're frozen/glitchy
}

// Inserts a new example into the examples table and returns the inserted row's id
Expand All @@ -16,12 +15,27 @@ function post(req, res, next) {
modelExample
.createExample(req.body)
.then((exampleId) => {
res.status(201).send({ exampleId: exampleId });
res.status(201).send({
exampleId: exampleId,
});
})
.catch(next);
}

function getExample(req, res, next) {
const id = req.params.id;
modelExample
.getExample(id)
.then((result) => {
res.status(200).send(result);
})
.catch(next);
}

// function updateExample()

module.exports = {
getAllExamples,
post,
getExample,
};
2 changes: 1 addition & 1 deletion middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function verifyUser(req, res, next) {
// if verification fails JWT throws an error, hence the try/catch
const tokenData = jwt.verify(token, SECRET);
model
.getUserById(tokenData.user_id)
.getUser(tokenData.user_id)
.then((user) => {
// attach the authenticated user to the request object
// so other handlers can access it without doing all this nonsense
Expand Down
41 changes: 41 additions & 0 deletions model/examples.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,48 @@ function createExample(example) {
});
}

function getExample(id) {
return db
.query("SELECT * FROM examples WHERE id=($1)", [id])
.then((res) => res.rows[0]);
}

function updateExample(id, newdata) {
return (
db
.query(
"UPDATE examples SET language=($1), title=($2), example=($3) WHERE id =($4) RETURNING *",
[newdata.language, newdata.title, newdata.example, id]
)
//must update ALL VALUES otherwise any value not updated will return NULL
.then((res) => res.rows[0])
);
}

// function updateExamplebyID(id, newdata) {
// // Setup static beginning of query
// var query = ["UPDATE examples"];
// query.push("SET");

// // Create another array storing each set command
// // and assigning a number value for parameterized query
// var set = [];
// Object.keys(newdata).forEach((key, i) => {
// set.push(key + " = ($" + (i + 1) + ")");
// });
// query.push(set.join(", "));

// // Add the WHERE statement to look up by id
// query.push("WHERE id = " + id + " RETURNING *");

// // Return a complete query string
// return query.join(" ");
// }

module.exports = {
getAllExamples,
createExample,
getExample,
updateExample,
// updateExamplebyID,
};
3 changes: 3 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ const PORT = process.env.PORT || 3000;
const server = express();
server.use(express.json());

server.get("/", examples.getAllExamples);
server.get("/example/:id", examples.getExample);

server.get("/", examples.getAllExamples);
server.post("/examples", auth, examples.post); // ADD AUTH MIDDLEWARE

Expand Down
84 changes: 73 additions & 11 deletions tests/model.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ const {
getUserById,
} = require("../model/users");

const {
getExample,
updateExample,
updateExamplebyID,
} = require("../model/examples");

test("DB tests are running!", (t) => {
const x = 5;
t.equal(x, 5, "this is working");
Expand Down Expand Up @@ -52,12 +58,36 @@ test("Returns user with a given email address", (t) => {
});
});

test("Returns a users row by id", (t) => {
test("Can get an example by id", (t) => {
build().then(() => {
getExample(1)
.then((res) => {
// console.log(res)
t.equal(res.language, "js");
t.equal(res.title, "Test example 1");
t.equal(res.example, "Example 1 code goes here.");
t.end();
})
.catch((err) => {
t.error(err);
t.end();
});
});
});

test("get update an example by id", (t) => {
build().then(() => {
getUserById("2")
const data = {
language: "sql",
// title: 'SQL example snippet',
example: "This is an example of SQL",
};
updateExamplebyID(4, data)
.then((res) => {
t.equal(res.username, "Tom");
t.equal(res.adminusr, false);
t.equal(res.language, "sql");
// t.equal(res.title, 'SQL example snippet')
t.equal(res.title, "Test example 4");
t.equal(res.example, "This is an example of SQL");
t.end();
})
.catch((err) => {
Expand All @@ -67,15 +97,47 @@ test("Returns a users row by id", (t) => {
});
});

// test.only("Can update an example by id without all values", (t) => {
// build().then(() => {
// const data = {
// language: "sql",
// example: "This is an example of SQL",
// };
// updateExample(4, data)
// .then((res) => {
// t.equal(res.language, "sql");
// // t.equal(res.title, 'SQL example snippet')
// t.equal(res.title, null);
// t.equal(res.example, "This is an example of SQL");
// t.end();
// })
// .catch((err) => {
// t.error(err);
// t.end();
// });
// });
// });

// test("Returns a users row by id", (t) => {
// build().then(() => {
// getUserById("2")
// .then((res) => {
// t.equal(res.username, "Tom");
// t.equal(res.adminusr, false);
// t.end();
// })
// .catch((err) => {
// t.error(err);
// t.end();
// });
// });
// });

// test("Returns error if no user found", (t) => {
// build().then(() => {
// t.throws(() => getUser("hello@iscool.com"))
// t.end();
// })
// .catch((err) => {
// t.error(err);
// t.end();
// });
// t.throws(() => getUser("hello@iscool.com"))
// t.end();
// })
// });

// test("Does not allow duplicate users when email is already in use", (t) => {
Expand Down
71 changes: 65 additions & 6 deletions tests/routes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,16 @@ test("Test /login route", (t) => {

test("Test /example POST route", (t) => {
build().then(() => {
const token = jwt.sign({ user_id: 2, admin: false }, process.env.SECRET, {
expiresIn: "1hr",
});
const token = jwt.sign(
{
user_id: 2,
admin: false,
},
process.env.SECRET,
{
expiresIn: "1hr",
}
);
supertest(server)
.post("/examples")
.set({
Expand All @@ -121,11 +128,63 @@ test("Test /example POST route", (t) => {
});
});

test("Test /login route", (t) => {
build().then(() => {
supertest(server)
.post("/login")
.send({
email: "roger@iscool.com",
password: "password",
})
.expect(200)
.expect("content-type", "application/json; charset=utf-8")
.end((err, res) => {
t.error(err, "HTTP status is 200 and application/json; charset=utf-8");
t.equals(typeof res.body, typeof {}, "Check an Object is returned");
t.notEquals(res.body.token, undefined, "Check that a token exists");
t.equals(
/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/.test(
res.body.token
),
true,
"Check for correct jwt token"
);
t.end();
});
});
});

test("Test GET/example/:id route", (t) => {
build().then(() => {
supertest(server)
.get("/example/2")
.expect(200)
.expect("content-type", "application/json; charset=utf-8")
.end((err, res) => {
t.error(err);
t.equals(typeof res.body, "object", "Check that res.body is an object");
t.equals(res.body.language, "sql", "Check the language is the same");
t.equals(
res.body.title,
"Test example 2",
"Check the title is the same"
);
t.end();
});
});
});
test.skip("Test /example POST route fails without valid auth token", (t) => {
build().then(() => {
const token = jwt.sign({ user_id: 2, admin: false }, process.env.SECRET, {
expiresIn: "1hr",
});
const token = jwt.sign(
{
user_id: 2,
admin: false,
},
process.env.SECRET,
{
expiresIn: "1hr",
}
);
supertest(server)
.post("/examples")
.set({
Expand Down

0 comments on commit 464b5aa

Please sign in to comment.