Skip to content
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

Lionel Mbayu #245

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
14 changes: 14 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"env": {
"commonjs": true,
"es2021": true,
"node": true,
"jest": true
},
"extends": "eslint:recommended",
"overrides": [],
"parserOptions": {
"ecmaVersion": "latest"
},
"rules": {}
}
130 changes: 130 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# 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
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://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/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"cSpell.words": ["Amebe", "Enoka", "Nange", "Talha"]
}
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@ For this project you will create a RESTful API using Node and Express, containin

Here is a checklist of tasks to help you put your project together:

- Generate a `.gitignore` file.
- Install express, [email protected], sqlite3 as plain dependencies.
- Alternatively install express, knex, @vscode/sqlite3 as plain dependencies.
- Install jest, eslint, nodemon, supertest, cross-env as dev-dependencies.
- Configure jest and eslint using `npx <libname> --init`.
- Create a `knexfile.js` with "development" and "testing" configurations.
- Create a `db-config.js` file that selects the correct configuration using the value of `process.env.NODE_ENV`.
- Generate a `.gitignore` file. - Done
- Install express, [email protected], sqlite3 as plain dependencies. - Done
- Alternatively install express, knex, @vscode/sqlite3 as plain dependencies. - Done
- Install jest, eslint, nodemon, supertest, cross-env as dev-dependencies. - done
- Configure jest and eslint using `npx <libname> --init`. - done
- Create a `knexfile.js` with "development" and "testing" configurations. - Done
- Create a `db-config.js` file that selects the correct configuration using the value of `process.env.NODE_ENV`. - Done
- Create migration and seed files.
- Put together "start", "server", "rollback", "migrate" and "seed" scripts in your `package.json`.
- Create a "test" script in your `package.json` using cross-env to inject a `NODE_ENV` of "testing".
- Create a basic express application with a few database access functions and a few endpoints.
- Put together "start", "server", "rollback", "migrate" and "seed" scripts in your `package.json`. - Done
- Create a "test" script in your `package.json` using cross-env to inject a `NODE_ENV` of "testing". - Done
- Create a basic express application with a few database access functions and a few endpoints. - Done
- Test your endpoints manually using Postman, HTTPie or similar.
- Test your endpoints with supertest.
22 changes: 22 additions & 0 deletions api/friends/friends-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const db = require('../../data/dbConfig');

const getAll = async () => {
return db('friends');
};

const getByID = (id) => {
return db('friends').where('id', id).first();
};

const insert = async (friend) => {
return await db('friends')
.insert(friend)
.then(([id]) => {
return db('friends').where('id', id).first();
});
};
module.exports = {
getAll,
getByID,
insert,
};
35 changes: 35 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const express = require('express');
const helmet = require('helmet');
const Friends = require('./friends/friends-model');

const server = express();

server.use(express.json());
server.use(helmet());

//eslint-disable-next-line
server.get('/', (req, res, next) => {
res.status(200).json({ api: 'up' });
});

server.get('/friends', async (req, res, next) => {
try {
const friends = await Friends.getAll();
res.status(200).json(friends);
} catch (err) {
next(err);
}
});

server.post('/friends', async (req, res) => {
res.status(201).json(await Friends.insert(req.body));
});

//eslint-disable-next-line
server.use((err, req, res, next) => {
res.status(500).json({
message: err.message,
stack: err.stack,
});
});
module.exports = server;
35 changes: 35 additions & 0 deletions api/server.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const db = require('../data/dbConfig');
const request = require('supertest');
const server = require('./server');

beforeAll(async () => {
await db.migrate.rollback();
await db.migrate.latest();
});

beforeEach(async () => {
await db.seed.run();
});

describe('[Get] /friends', () => {
test('responds with 200 Ok', async () => {
const res = await request(server).get('/friends');
expect(res.status).toBe(200);
});
test('responds with all the hobbits', async () => {
const res = await request(server).get('/friends');
expect(res.body).toHaveLength(4);
});
});

describe('[POST] /friends', () => {
const name = { name: 'Nange' };
test('adds a friend to the database', async () => {
await request(server).post('/friends').send(name);
expect(await db('friends')).toHaveLength(5);
});
test('responds with the new friend', async () => {
const res = await request(server).post('/friends').send(name);
expect(res.body).toMatchObject(name);
});
});
7 changes: 7 additions & 0 deletions data/dbConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const knex = require('knex');

const config = require('../knexfile.js');

const environment = process.env.NODE_ENV || 'development';

module.exports = knex(config[environment]);
Binary file added data/lionel.db3
Binary file not shown.
Binary file added data/lionelTest.db3
Binary file not shown.
18 changes: 18 additions & 0 deletions data/migrations/20230525234453_firstmigration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = function (knex) {
return knex.schema.createTable('friends', (tbl) => {
tbl.increments();
tbl.string('name', 150).unique().notNullable();
});
};

/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = function (knex) {
return knex.schema.dropTableIfExists('friends');
};
14 changes: 14 additions & 0 deletions data/seeds/firstseed.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.seed = async function (knex) {
// Deletes ALL existing entries
await knex('friends').del();
await knex('friends').insert([
{ name: 'Enoka' },
{ name: 'Talha' },
{ name: 'Amebe' },
{ name: 'Jeff' },
]);
};
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require('dotenv').config();

const server = require('./api/server.js');

const port = process.env.PORT || 9000;
server.listen(port, () => console.log(`\n** server up on port ${port} **\n`));
22 changes: 22 additions & 0 deletions knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const common = {
client: 'sqlite3',
useNullAsDefault: true,
migrations: { directory: './data/migrations' },
seeds: { directory: './data/seeds' },
};

module.exports = {
development: {
...common,
connection: {
filename: './data/lionel.db3',
},
},
testing: {
...common,
connection: {
filename: './data/lionelTest.db3',
},
},
production: {},
};
Loading