Skip to content

Commit 43d1fe3

Browse files
knex work, seeds, migrations. Test file set up just a tiny bit more.
1 parent 4199502 commit 43d1fe3

File tree

9 files changed

+157
-17
lines changed

9 files changed

+157
-17
lines changed

app.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ require('babel-polyfill');
1010
if (env === 'development') { require('babel-register'); }
1111

1212
const app = require(src).default;
13-
app.listen(port);
13+
14+
//Here we're assigning the server to a variable because
15+
//we're going to want to manually rip down the server in testing
16+
const server = app.listen(port);
1417
console.log('Server running at ' + port);
15-
console.log("Running in " + process.env.NODE_ENV + " v" + process.env.npm_package_version);
18+
console.log("Running in " + process.env.NODE_ENV + " v" + process.env.npm_package_version);
19+
20+
//Exporting the actual server here for testing availability
21+
module.exports = {server: server}

knexfile.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//This knexfile is just used for migrations. The actual
2+
//db object is built in ./src/db/db and is used throughout the app.
3+
4+
require('dotenv').config();
5+
6+
module.exports = {
7+
8+
client: 'mysql',
9+
connection: {
10+
host: process.env.DB_HOST,
11+
port: process.env.DB_PORT,
12+
user: process.env.DB_USER,
13+
password: process.env.DB_PASSWORD,
14+
database: process.env.DB_DATABASE,
15+
},
16+
migrations: {
17+
directory: './src/db/migrations',
18+
},
19+
seeds: {
20+
directory: './src/db/seeds/dev',
21+
},
22+
23+
};

package-lock.json

Lines changed: 6 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
11
{
22
"name": "koa-vue-notes-api",
3-
"version": "1.0.4",
3+
"version": "1.1.1",
44
"description": "A SPA using Koa as the backend and Vue as the frontend.",
55
"author": "John Datserakis",
66
"private": false,
77
"scripts": {
8-
"start": "node app.js",
9-
"watch": "nodemon --exec npm run start",
10-
"test": "jest --forceExit",
11-
"build": "babel src -d build && npm run pretty",
12-
"pretty": "prettier --write --print-width 80 --single-quote --trailing-comma es5 --tab-width 4 --no-semi 'src/**/*.js' 'models/**/*.js' 'middleware/**/*.js' 'config/**/*.js'",
13-
"start-production": "pm2 start ecosystem.json",
14-
"clean": "npm run clean:dist && npm run clean:tmp"
8+
"watch": "NODE_ENV=development nodemon app.js --exec",
9+
"test": "NODE_ENV=testing jest -forceExit",
10+
"build": "NODE_ENV=production babel src -d build && npm run pretty",
11+
"pretty": "prettier --write --print-width 80 --single-quote --trailing-comma es5 --tab-width 4 --no-semi 'src/**/*.js'",
12+
"start-production": "NODE_ENV=production pm2 start ecosystem.json",
13+
"clean": "npm cache clean --force"
1514
},
1615
"license": "MIT",
1716
"homepage": "https://github.com/OrKoN/koa2-example-app#readme",
@@ -21,6 +20,7 @@
2120
"bcrypt": "^1.0.2",
2221
"date-fns": "^1.28.5",
2322
"dotenv": "^4.0.0",
23+
"faker": "^4.1.0",
2424
"fs-extra": "^4.0.0",
2525
"install": "^0.10.1",
2626
"ioredis": "^3.1.1",

readme.md

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ This is a simple SPA built using [Koa](http://koajs.com/) (2.3) as the backend a
2828
- Prettier
2929
- Babel
3030
- PM2
31-
- MySQL with Knex
31+
- MySQL
32+
- Knex with migrations and seeds
33+
- Faker
3234
- log4js
3335
- And more...
3436

@@ -49,6 +51,25 @@ npm run start-production
4951

5052
# run prettier on the project
5153
npm run pretty
54+
55+
# knex migration examples
56+
# (from command line in root directory with knex installed globally)
57+
# (*make* commands are just here to show syntax)
58+
59+
# make migration
60+
knex migrate:make create_users_table
61+
62+
# migrate latest
63+
knex migrate:latest
64+
65+
# rollback
66+
knex migrate:rollback
67+
68+
# make seed
69+
knex seed:make seed_users
70+
71+
# run all seeds
72+
knex seed:run
5273
```
5374

5475
## General Information
@@ -59,9 +80,9 @@ I've liberally commented the code and tried to balance the project in a way that
5980

6081
Having used mainly PHP for the backend in the past - I am very glad I checked out Koa as I think it is absolutely awesome in the way it handles the server code. Same thing with Vue - I've used mainly jQuery in the past - albeit with the really structured Revealing-Module-Pattern - and using Vue was such a pleasure. You can really tell right away what kind of power a well-structured library can give you.
6182

62-
You'll need to create a `.env` file and place it in the root of your directory. Take a look at `example.env` and add your information as needed. For `JWT_ACCESS_TOKEN_EXPIRATION_TIME` you can set it to 5m, 5w, 5d etc.
83+
You'll need to create a `.env` file and place it in the root of your directory. Take a look at `example.env` and add your information as needed. For `JWT_ACCESS_TOKEN_EXPIRATION_TIME` you can set it to 5m, 5w, 5d etc - although 5m is what I'm using at the moment. Note - we don't set the NODE_ENV variable in the `.env` - we set it in the npm scripts. This lets us specifically set different environments as needed.
6384

64-
This project only responds and listens in json. Keep that in mind when send requests through Postman or your frontend.
85+
This project only responds and listens in JSON. Keep that in mind when send requests through Postman or your frontend.
6586

6687
### User Authentication Process
6788

src/db/db.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,16 @@ const config = {
1010
database: process.env.DB_DATABASE,
1111
},
1212
migrations: {
13-
directory: __dirname + '/src/db/migrations',
13+
directory: './src/db/migrations',
1414
},
1515
}
1616

17+
//Here we check to see if we are in testing mode. If we are,
18+
//we set the database name to one with a '_tests' at the end,
19+
//which we'll build and tear-down for each test.
20+
if (process.env.NODE_ENV === 'testing') {
21+
config.connection.database = process.env.DB_DATABASE + '_tests'
22+
}
23+
1724
const db = knex(config)
1825
export default db

src/db/seeds/dev/seed_notes.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
const faker = require('faker');
2+
3+
exports.seed = async function(knex, Promise) {
4+
5+
//Make 100 notes for 10 different users
6+
let seedData = [];
7+
for (let i = 0; i < 100; i++) {
8+
let testNote = {
9+
userId: faker.random.number({min: 1, max: 10}),
10+
title: faker.lorem.sentence(),
11+
content: faker.lorem.sentences(Math.floor(Math.random() * 10) + 1)
12+
}
13+
seedData.push(testNote)
14+
}
15+
16+
// Deletes ALL existing entries
17+
await knex('notes').truncate()
18+
19+
//Insert users
20+
await knex('notes').insert(seedData);
21+
22+
};

src/db/seeds/dev/seed_users.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
const faker = require('faker');
2+
const bcrypt = require('bcrypt');
3+
4+
exports.seed = async function(knex, Promise) {
5+
6+
//Make 10 users using faker. Note: we're also bcrypting
7+
//the passwords to make it exactly like the real app. All their
8+
//passwords will be 'secret'
9+
let seedData = [];
10+
for (let i = 0; i < 10; i++) {
11+
let password = 'secret'
12+
try {
13+
password = await bcrypt.hash(password, 12)
14+
} catch (error) {
15+
throw new Error('PASSWORD_ENCRIPTION_ERROR')
16+
}
17+
18+
let testUser = {
19+
token: faker.internet.password(),
20+
firstName: faker.name.firstName(),
21+
lastName: faker.name.lastName(),
22+
username: faker.internet.userName(),
23+
email: faker.internet.email(),
24+
password: password,
25+
}
26+
seedData.push(testUser)
27+
}
28+
29+
// Deletes ALL existing entries
30+
await knex('users').truncate()
31+
32+
//Insert users
33+
await knex('users').insert(seedData);
34+
35+
};

tests/test.js

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,29 @@
1-
const axios = require('axios')
2-
const app = require('../app')
1+
// //This starts the app up
2+
import {server} from '../app'
3+
4+
//Set up axios a little bit
5+
import axios from 'axios'
36
const url = `http://localhost:4000`
47
const request = axios.create({ baseURL: url })
58

9+
//Grab the db variable
10+
import db from '../src/db/db'
11+
12+
//Before each test we are going to rollback and
13+
//migrate out database to its latest version
14+
beforeEach(async () => {
15+
await db.migrate.rollback()
16+
await db.migrate.latest()
17+
// await knex.seed.run()
18+
});
19+
20+
//After all the tests are done we're going to close our server
21+
//and rollback our database.
22+
afterAll(async () => {
23+
await db.migrate.rollback()
24+
return server.close()
25+
});
26+
627
it('returns homepage', async () => {
728
expect.assertions(1)
829
const response = await request.get('/')

0 commit comments

Comments
 (0)