Skip to content
This repository has been archived by the owner on Feb 28, 2020. It is now read-only.

Commit

Permalink
Add a seed script to insert a test user. #1
Browse files Browse the repository at this point in the history
  • Loading branch information
thebearingedge committed Mar 14, 2019
1 parent 60f1ae7 commit f4723f7
Show file tree
Hide file tree
Showing 12 changed files with 124 additions and 31 deletions.
5 changes: 5 additions & 0 deletions .env.example
Expand Up @@ -13,3 +13,8 @@ POSTGRES_DB=poke-admin

# Test Variables
API_URL=http://localhost:3000

# Admin User Variables
ADMIN_USER_ID=21247c46-90db-469d-a3fc-41febde52bf0
ADMIN_USERNAME=admin
ADMIN_PASSWORD=password
24 changes: 9 additions & 15 deletions api/test/index.js
@@ -1,29 +1,28 @@
import axios from 'axios'
import bcrypt from 'bcrypt'
import chai from 'chai'
import faker from 'faker'
import noop from 'lodash/noop'
import { chaiStruct } from 'chai-struct'
import createApi from '../create-api'
import { knex, redis } from '../../database/connections'
import * as admin from '../../database/seeds/admin'
import { createKnex, createRedis } from '../../database/connections'

chai.use(chaiStruct)

let server
let knex
let redis
let _knex
let _redis
let _trx

before('start root transaction and insert test user into database', done => {
knex = createKnex()
redis = createRedis()
knex.transaction(trx => {
_trx = trx
;(async () => {
try {
const { password: unhashed } = TEST_USER
const password = await bcrypt.hash(unhashed, 1)
await _trx
.insert({ ...TEST_USER, password })
.into('users')
await admin.seed(trx)
done()
}
catch (err) {
Expand Down Expand Up @@ -74,10 +73,5 @@ export const client = axios.create({
baseURL: process.env.API_URL
})

export const TEST_USER = {
userId: faker.random.uuid(),
username: 'admin',
password: 'password'
}

export { expect } from 'chai'
export const { expect } = chai
export const { user: TEST_USER } = admin
12 changes: 12 additions & 0 deletions client/lib/authorize.js
@@ -0,0 +1,12 @@
import noop from 'lodash/noop'

export default function authorize(getInitialProps = noop) {
return ({ res, router, session, isServer, ...ctx }) => {
if (!session.user) {
return isServer
? res.redirect('/login')
: router.replace('/login')
}
return getInitialProps({ res, router, session, isServer, ...ctx })
}
}
1 change: 1 addition & 0 deletions client/lib/index.js
@@ -1 +1,2 @@
export { default as authorize } from './authorize'
export { default as isServer } from './is-server'
5 changes: 4 additions & 1 deletion client/pages/index.jsx
@@ -1,4 +1,5 @@
import { Consumer } from '../lib'
import { authorize } from '../lib'
import { Consumer } from '../services'

export default function Index() {
return (
Expand All @@ -11,3 +12,5 @@ export default function Index() {
</Consumer>
)
}

Index.getInitialProps = authorize()
4 changes: 2 additions & 2 deletions database/connections.js
Expand Up @@ -6,13 +6,13 @@ import camelKeys from './lib/camel-keys'

promisifyAll(RedisClient.prototype)

export const knex = Knex({
export const createKnex = () => Knex({
client: 'pg',
connection: process.env.POSTGRES_URL,
postProcessResponse: camelKeys,
wrapIdentifier: (value, wrap) => wrap(snakeCase(value))
})

export const redis = new RedisClient({
export const createRedis = () => new RedisClient({
url: process.env.REDIS_URL
})
19 changes: 19 additions & 0 deletions database/seeds/__dev__.js
@@ -0,0 +1,19 @@
import path from 'path'
import { createKnex, createRedis } from '../connections'

(async () => {
const knex = createKnex()
const redis = createRedis()
try {
await redis.flushallAsync()
await knex.seed.run({
directory: path.join(__dirname, 'dev/')
})
await knex.destroy()
await redis.quitAsync()
}
catch (err) {
console.error(err)
process.exit(1)
}
})()
16 changes: 16 additions & 0 deletions database/seeds/admin.js
@@ -0,0 +1,16 @@
import bcrypt from 'bcrypt'

export const user = {
userId: process.env.ADMIN_USER_ID,
username: process.env.ADMIN_USERNAME,
password: process.env.ADMIN_PASSWORD
}

export async function seed(knex) {
const saltRounds = process.env.NODE_ENV === 'production' ? 12 : 1
const password = await bcrypt.hash(user.password, saltRounds)
await knex.raw('truncate table users cascade')
await knex
.insert({ ...user, password })
.into('users')
}
26 changes: 26 additions & 0 deletions database/seeds/dev/index.js
@@ -0,0 +1,26 @@
import chalk from 'chalk'
import * as admin from '../admin'

export async function seed(knex) {

const trySeed = (knex => async (script, description) => {
/* eslint-disable no-console */
console.log(chalk.white(`Running seed script for ${description}...`))
try {
await script.seed(knex)
console.log(chalk.green('done'))
}
catch (err) {
console.error(err)
console.error(chalk.red(`ERROR:Failed to run seed script for ${description}.`))
process.exit(1)
}
})(knex)

console.log('\n')

await trySeed(admin, 'admin user')
await admin.seed(knex)

console.log('\n')
}
32 changes: 23 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions package.json
Expand Up @@ -10,9 +10,10 @@
"db:up": "pg-bump up",
"db:down": "pg-bump down",
"db:cycle": "run-s -s db:down db:up",
"db:seed": "node -r dotenv/config -r esm database/seeds/__dev__.js",
"build": "next build client/",
"start": "node -r dotenv/config -r esm .",
"dev": "run-s -s db:cycle && nodemon .",
"dev": "run-s -s db:cycle db:seed && nodemon .",
"lint": "eslint --fix .",
"test:api": "mocha --opts api/test/mocha.opts",
"tdd:api": "run-s -s db:cycle 'test:api -- -w -R min'",
Expand Down Expand Up @@ -43,7 +44,7 @@
"text-summary"
],
"include": [
"**/*.js"
"api/**/*.js"
],
"exclude": [
"**/test/**",
Expand Down Expand Up @@ -142,6 +143,7 @@
"bcrypt": "3.0.4",
"bluebird": "3.5.3",
"boom": "7.3.0",
"chalk": "2.4.2",
"connect-redis": "3.4.0",
"dotenv": "6.2.0",
"esm": "3.2.14",
Expand Down Expand Up @@ -175,7 +177,6 @@
"eslint-plugin-promise": "4.0.1",
"eslint-plugin-react": "7.12.4",
"eslint-plugin-standard": "4.0.0",
"faker": "4.1.0",
"husky": "1.3.1",
"lint-staged": "8.1.5",
"mocha": "6.0.2",
Expand Down
4 changes: 3 additions & 1 deletion server/index.js
@@ -1,7 +1,9 @@
import createServer from './create-server'
import { knex, redis } from '../database/connections'
import { createKnex, createRedis } from '../database/connections'

const dev = process.env.NODE_ENV !== 'production'
const knex = createKnex()
const redis = createRedis()

;(async () => {
const server = await createServer({ dev, knex, redis })
Expand Down

0 comments on commit f4723f7

Please sign in to comment.