Merge branch 'master' into dependabot/npm_and_yarn/eslint-5.14.1

This commit is contained in:
Robert Schäfer 2019-02-26 16:15:38 +01:00 committed by GitHub
commit 44f5ccac77
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
43 changed files with 692 additions and 790 deletions

View File

@ -16,10 +16,12 @@ before_install:
- curl -L https://github.com/docker/compose/releases/download/${DOCKER_COMPOSE_VERSION}/docker-compose-`uname -s`-`uname -m` > docker-compose
- chmod +x docker-compose
- sudo mv docker-compose /usr/local/bin
- yarn global add wait-on
install:
- docker build --build-arg BUILD_COMMIT=$TRAVIS_COMMIT --target production -t humanconnection/nitro-backend:latest .
- docker-compose -f docker-compose.yml -f docker-compose.travis.yml up -d
- wait-on http://localhost:7474 && docker-compose exec neo4j migrate
script:
- docker-compose exec backend yarn run lint

View File

@ -10,15 +10,15 @@
> This Prototype tries to resolve the biggest hurdle of connecting
> our services together. This is not possible in a sane way using
> our current approach.
>
> With this Prototype we can explore using the combination of
> our current approach.
>
> With this Prototype we can explore using the combination of
> GraphQL and the Neo4j Graph Database for achieving the connected
> nature of a social graph with better development experience as we
> do not need to connect data by our own any more through weird table
> structures etc.
>
>
> #### Advantages:
> - easer data structure
> - better connected data
@ -26,10 +26,10 @@
> - more performant and better to understand API
> - better API client that uses caching
>
> We still need to evaluate the drawbacks and estimate the development
> We still need to evaluate the drawbacks and estimate the development
> cost of such an approach
## How to get in touch
## How to get in touch
Connect with other developers over [Discord](https://discord.gg/6ub73U3)
## Quick Start
@ -42,6 +42,10 @@ Before you start, fork the repository using the fork button above, then clone it
Run:
```sh
docker-compose up
# create indices etc.
docker-compose exec neo4j migrate
# if you want seed data
# open another terminal and run
docker-compose exec backend yarn run db:seed
@ -101,7 +105,7 @@ _.env_
```yaml
NEO4J_URI=bolt://localhost:7687
NEO4J_USER=neo4j
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=letmein
```
@ -123,7 +127,7 @@ Just set `MOCK=true` inside `.env` or pass it on application start.
## Seed and Reset the Database
Optionally you can seed the GraphQL service by executing mutations that
Optionally you can seed the GraphQL service by executing mutations that
will write sample data to the database:
```bash
@ -159,7 +163,7 @@ npm run test
- [x] check if sorting is working
- [x] check if pagination is working
- [ ] check if upload is working (using graphql-yoga?)
- [x] evaluate middleware
- [x] evaluate middleware
- [ ] ignore Posts and Comments by blacklisted Users

View File

@ -0,0 +1,18 @@
version: "3.7"
services:
neo4j:
environment:
- NEO4J_AUTH=none
ports:
- 7687:7687
- 7474:7474
backend:
ports:
- 4001:4001
- 4123:4123
image: humanconnection/nitro-backend:builder
build:
context: .
target: builder
command: yarn run test:cypress

View File

@ -11,6 +11,13 @@ services:
- /nitro-backend/node_modules
command: yarn run dev
neo4j:
environment:
- NEO4J_AUTH=none
ports:
- 7687:7687
- 7474:7474
volumes:
- neo4j-data:/data
volumes:
neo4j-data:

9
docker-compose.prod.yml Normal file
View File

@ -0,0 +1,9 @@
version: "3.7"
services:
neo4j:
environment:
- NEO4J_PASSWORD=letmein
backend:
environment:
- NEO4J_PASSWORD=letmein

View File

@ -1,6 +1,12 @@
version: "3.7"
services:
neo4j:
environment:
- NEO4J_AUTH=none
ports:
- 7687:7687
- 7474:7474
backend:
image: humanconnection/nitro-backend:builder
build:

View File

@ -27,14 +27,7 @@ services:
context: neo4j
networks:
- hc-network
volumes:
- neo4j-data:/data
environment:
- NEO4J_AUTH=none
networks:
hc-network:
name: hc-network
volumes:
neo4j-data:

View File

@ -1,2 +1,3 @@
FROM neo4j:3.5.0
RUN wget https://github.com/neo4j-contrib/neo4j-apoc-procedures/releases/download/3.5.0.1/apoc-3.5.0.1-all.jar -P plugins/
COPY migrate.sh /usr/local/bin/migrate

18
neo4j/migrate.sh Executable file
View File

@ -0,0 +1,18 @@
#!/usr/bin/env bash
# If the user has the password `neo4j` this is a strong indicator, that we are
# the initial default user. Before we can create constraints, we have to change
# the default password. This is a security feature of neo4j.
if echo ":exit" | cypher-shell --password neo4j 2> /dev/null ; then
echo "CALL dbms.security.changePassword('${NEO4J_PASSWORD}');" | cypher-shell --password neo4j
fi
set -e
echo '
CALL db.index.fulltext.createNodeIndex("full_text_search",["Post"],["title", "content"]);
CREATE CONSTRAINT ON (p:Post) ASSERT p.slug IS UNIQUE;
CREATE CONSTRAINT ON (c:Category) ASSERT c.slug IS UNIQUE;
CREATE CONSTRAINT ON (u:User) ASSERT u.slug IS UNIQUE;
CREATE CONSTRAINT ON (o:Organization) ASSERT o.slug IS UNIQUE;
' | cypher-shell

View File

@ -13,6 +13,7 @@
"dev:debug": "nodemon --exec babel-node --inspect=0.0.0.0:9229 src/index.js",
"lint": "eslint src --config .eslintrc.js",
"test": "nyc --reporter=text-lcov yarn run test:jest",
"test:cypress": "run-p --race test:before:*",
"test:before:server": "cross-env GRAPHQL_URI=http://localhost:4123 GRAPHQL_PORT=4123 babel-node src/ 2> /dev/null",
"test:before:seeder": "cross-env GRAPHQL_URI=http://localhost:4001 GRAPHQL_PORT=4001 PERMISSIONS=disabled babel-node src/ 2> /dev/null",
"test:jest:cmd": "wait-on tcp:4001 tcp:4123 && jest --forceExit --detectOpenHandles --runInBand",
@ -21,9 +22,8 @@
"test:jest:debug": "run-p --race test:before:* 'test:jest:cmd:debug {@}' --",
"test:coverage": "nyc report --reporter=text-lcov > coverage.lcov",
"db:script:seed": "wait-on tcp:4001 && babel-node src/seed/seed-db.js",
"db:script:reset": "wait-on tcp:4001 && babel-node src/seed/reset-db.js",
"db:seed": "$npm_package_config_no_auth run-p --race dev db:script:seed",
"db:reset": "$npm_package_config_no_auth run-p --race dev db:script:reset"
"db:reset": "babel-node src/seed/reset-db.js",
"db:seed": "$npm_package_config_no_auth run-p --race dev db:script:seed"
},
"author": "Human Connection gGmbH",
"license": "MIT",

View File

@ -1,4 +1,3 @@
// import { neo4jgraphql } from "neo4j-graphql-js"
import fs from 'fs'
import path from 'path'
import bcrypt from 'bcryptjs'
@ -6,6 +5,7 @@ import generateJwt from './jwt/generateToken'
import uuid from 'uuid/v4'
import { fixUrl } from './middleware/fixImageUrlsMiddleware'
import { AuthenticationError } from 'apollo-server'
import { neo4jgraphql } from 'neo4j-graphql-js'
export const typeDefs =
fs.readFileSync(process.env.GRAPHQL_SCHEMA || path.join(__dirname, 'schema.graphql'))
@ -161,6 +161,22 @@ export const resolvers = {
// TODO: output Report compatible object
return data
},
CreatePost: async (object, params, ctx, resolveInfo) => {
const result = await neo4jgraphql(object, params, ctx, resolveInfo, false)
const session = ctx.driver.session()
await session.run(
'MATCH (author:User {id: $userId}), (post:Post {id: $postId}) ' +
'MERGE (post)<-[:WROTE]-(author) ' +
'RETURN author', {
userId: ctx.user.id,
postId: result.id
})
session.close()
return result
}
}
}

View File

@ -1,10 +1,30 @@
import { GraphQLClient, request } from 'graphql-request'
import Factory from './seed/factories'
import { GraphQLClient, request } from 'graphql-request'
import jwt from 'jsonwebtoken'
import { host, login } from './jest/helpers'
const factory = Factory()
beforeEach(async () => {
await factory.create('User', {
email: 'test@example.org',
password: '1234'
})
})
afterEach(async () => {
await factory.cleanDatabase()
})
describe('isLoggedIn', () => {
describe('unauthenticated', () => {
it('returns false', async () => {
const query = '{ isLoggedIn }'
await expect(request(host, query)).resolves.toEqual({ isLoggedIn: false })
})
})
})
describe('login', () => {
const mutation = (params) => {
const { email, password } = params
@ -16,48 +36,85 @@ describe('login', () => {
}`
}
describe('given an existing user', () => {
beforeEach(async () => {
await factory.create('user', {
email: 'test@example.org',
password: '1234'
describe('ask for a `token`', () => {
describe('with valid email/password combination', () => {
it('responds with a JWT token', async () => {
const data = await request(host, mutation({
email: 'test@example.org',
password: '1234'
}))
const { token } = data.login
jwt.verify(token, process.env.JWT_SECRET, (err, data) => {
expect(data.email).toEqual('test@example.org')
expect(err).toBeNull()
})
})
})
afterEach(async () => {
await factory.cleanDatabase()
describe('with a valid email but incorrect password', () => {
it('responds with "Incorrect email address or password."', async () => {
await expect(
request(host, mutation({
email: 'test@example.org',
password: 'wrong'
}))
).rejects.toThrow('Incorrect email address or password.')
})
})
describe('asking for a `token`', () => {
describe('with valid email/password combination', () => {
it('responds with a JWT token', async () => {
const data = await request(host, mutation({ email: 'test@example.org', password: '1234' }))
const { token } = data.login
jwt.verify(token, process.env.JWT_SECRET, (err, data) => {
expect(data.email).toEqual('test@example.org')
expect(err).toBeNull()
})
})
describe('with a non-existing email', () => {
it('responds with "Incorrect email address or password."', async () => {
await expect(
request(host, mutation({
email: 'non-existent@example.org',
password: 'wrong'
}))
).rejects.toThrow('Incorrect email address or password.')
})
})
})
})
describe('CreatePost', () => {
describe('unauthenticated', () => {
let client
it('throws authorization error', async () => {
client = new GraphQLClient(host)
await expect(client.request(`mutation {
CreatePost(
title: "I am a post",
content: "Some content"
) { slug }
}`)).rejects.toThrow('Not Authorised')
})
describe('authenticated', () => {
let headers
let response
beforeEach(async () => {
headers = await login({ email: 'test@example.org', password: '1234' })
client = new GraphQLClient(host, { headers })
response = await client.request(`mutation {
CreatePost(
title: "A title",
content: "Some content"
) { title, content }
}`, { headers })
})
describe('with a valid email but incorrect password', () => {
it('responds with "Incorrect email address or password."', async () => {
try {
await request(host, mutation({ email: 'test@example.org', password: 'wrong' }))
} catch (error) {
expect(error.response.errors[0].message).toEqual('Incorrect email address or password.')
}
})
it('creates a post', () => {
expect(response).toEqual({ CreatePost: { title: 'A title', content: 'Some content' } })
})
describe('with a non-existing email', () => {
it('responds with "Incorrect email address or password."', async () => {
try {
await request(host, mutation({ email: 'non-existent@example.org', password: 'wrong' }))
} catch (error) {
expect(error.response.errors[0].message).toEqual('Incorrect email address or password.')
it('assigns the authenticated user as author', async () => {
const { User } = await client.request(`{
User(email:"test@example.org") {
contributions {
title
}
}
})
}`, { headers })
expect(User).toEqual([ { contributions: [ { title: 'A title' } ] } ])
})
})
})
@ -65,11 +122,11 @@ describe('login', () => {
describe('report', () => {
beforeEach(async () => {
await factory.create('user', {
await factory.create('User', {
email: 'test@example.org',
password: '1234'
})
await factory.create('user', {
await factory.create('User', {
id: 'u2',
name: 'abusive-user',
role: 'user',

View File

@ -7,15 +7,30 @@ export default {
const result = await resolve(root, args, context, info)
return result
},
UpdatePost: async (resolve, root, args, context, info) => {
args.contentExcerpt = trunc(args.content, 120).html
const result = await resolve(root, args, context, info)
return result
},
CreateComment: async (resolve, root, args, context, info) => {
args.contentExcerpt = trunc(args.content, 180).html
const result = await resolve(root, args, context, info)
return result
},
UpdateComment: async (resolve, root, args, context, info) => {
args.contentExcerpt = trunc(args.content, 180).html
const result = await resolve(root, args, context, info)
return result
},
CreateOrganization: async (resolve, root, args, context, info) => {
args.descriptionExcerpt = trunc(args.description, 120).html
const result = await resolve(root, args, context, info)
return result
},
UpdateOrganization: async (resolve, root, args, context, info) => {
args.descriptionExcerpt = trunc(args.description, 120).html
const result = await resolve(root, args, context, info)
return result
}
}
}

View File

@ -0,0 +1,28 @@
import cloneDeep from 'lodash/cloneDeep'
const includeId = async (resolve, root, args, context, resolveInfo) => {
// Keeping the graphql resolveInfo untouched ensures that we don't add the
// following attributes to the result set returned to the graphQL client.
// We only want to pass these attributes to our resolver for internal
// purposes e.g. authorization.
const copy = cloneDeep(resolveInfo)
copy.fieldNodes[0].selectionSet.selections.unshift({
kind: 'Field',
name: { kind: 'Name', value: 'id' }
})
return resolve(root, args, context, copy)
}
export default {
Query: {
User: (resolve, root, args, context, info) => {
return includeId(resolve, root, args, context, info)
}
},
Mutation: {
CreatePost: (resolve, root, args, context, info) => {
return includeId(resolve, root, args, context, info)
}
}
}

View File

@ -7,6 +7,7 @@ import dateTimeMiddleware from './dateTimeMiddleware'
import xssMiddleware from './xssMiddleware'
import permissionsMiddleware from './permissionsMiddleware'
import userMiddleware from './userMiddleware'
import idMiddleware from './idMiddleware'
export default schema => {
let middleware = [
@ -17,7 +18,8 @@ export default schema => {
xssMiddleware,
fixImageUrlsMiddleware,
softDeleteMiddleware,
userMiddleware
userMiddleware,
idMiddleware
]
// add permisions middleware at the first position (unless we're seeding)

View File

@ -16,7 +16,7 @@ const isModerator = rule()(async (parent, args, ctx, info) => {
})
*/
const isOwner = rule({ cache: 'no_cache' })(async (parent, args, ctx, info) => {
const isMyOwn = rule({ cache: 'no_cache' })(async (parent, args, ctx, info) => {
return ctx.user.id === parent.id
})
@ -28,13 +28,16 @@ const permissions = shield({
// customers: and(isAuthenticated, isAdmin)
},
Mutation: {
CreatePost: isAuthenticated,
// TODO UpdatePost: isOwner,
// TODO DeletePost: isOwner,
report: isAuthenticated
// addFruitToBasket: isAuthenticated
// CreateUser: allow,
},
User: {
email: isOwner,
password: isOwner
email: isMyOwn,
password: isMyOwn
}
// Post: isAuthenticated
})

View File

@ -1,16 +1,18 @@
import { create, cleanDatabase } from '../seed/factories'
import Factory from '../seed/factories'
import { host, login } from '../jest/helpers'
import { GraphQLClient } from 'graphql-request'
const factory = Factory()
describe('authorization', () => {
describe('given two existing users', () => {
beforeEach(async () => {
await create('user', {
await factory.create('User', {
email: 'owner@example.org',
name: 'Owner',
password: 'iamtheowner'
})
await create('user', {
await factory.create('User', {
email: 'someone@example.org',
name: 'Someone else',
password: 'else'
@ -18,51 +20,63 @@ describe('authorization', () => {
})
afterEach(async () => {
await cleanDatabase()
await factory.cleanDatabase()
})
describe('access email address', () => {
let headers = {}
const action = async (headers) => {
let loginCredentials = null
const action = async () => {
if (loginCredentials) {
headers = await login(loginCredentials)
}
const graphQLClient = new GraphQLClient(host, { headers })
return graphQLClient.request(`{
User(name: "Owner") {
email
}
}`)
return graphQLClient.request('{User(name: "Owner") { email } }')
}
describe('not logged in', async () => {
it('rejects', async () => {
await expect(action()).rejects.toThrow('Not Authorised!')
})
it('does not expose the owner\'s email address', async () => {
try {
await action(headers)
await action()
} catch (error) {
expect(error.response.errors[0].message).toEqual('Not Authorised!')
expect(error.response.data).toEqual({ User: [ { email: null } ] })
}
})
})
describe('as owner', () => {
it('exposes the owner\'s email address', async () => {
headers = await login({
beforeEach(() => {
loginCredentials = {
email: 'owner@example.org',
password: 'iamtheowner'
})
expect(await action(headers)).toEqual({ User: [ { email: 'owner@example.org' } ] })
}
})
it('exposes the owner\'s email address', async () => {
await expect(action()).resolves.toEqual({ User: [ { email: 'owner@example.org' } ] })
})
})
describe('as someone else', () => {
it('does not expose the owner\'s email address', async () => {
headers = await login({
describe('authenticated as another user', () => {
beforeEach(async () => {
loginCredentials = {
email: 'someone@example.org',
password: 'else'
})
}
})
it('rejects', async () => {
await expect(action()).rejects.toThrow('Not Authorised!')
})
it('does not expose the owner\'s email address', async () => {
try {
await action(headers)
await action()
} catch (error) {
expect(error.response.errors[0].message).toEqual('Not Authorised!')
expect(error.response.data).toEqual({ User: [ { email: null } ] })
}
})

View File

@ -1,40 +1,34 @@
import slug from 'slug'
import uniqueSlug from './slugify/uniqueSlug'
const isUniqueFor = (context, type) => {
return async (slug) => {
const session = context.driver.session()
const response = await session.run(
`MATCH(p:${type} {slug: $slug }) return p.slug`, {
slug
})
session.close()
return response.records.length === 0
}
}
export default {
Mutation: {
CreatePost: async (resolve, root, args, context, info) => {
args.slug = slug(args.title, {
lower: true
})
const result = await resolve(root, args, context, info)
return result
args.slug = args.slug || await uniqueSlug(args.title, isUniqueFor(context, 'Post'))
return resolve(root, args, context, info)
},
CreateUser: async (resolve, root, args, context, info) => {
if (!args.slug) {
args.slug = slug(args.name, {
lower: true
})
}
const result = await resolve(root, args, context, info)
return result
args.slug = args.slug || await uniqueSlug(args.name, isUniqueFor(context, 'User'))
return resolve(root, args, context, info)
},
CreateOrganization: async (resolve, root, args, context, info) => {
if (!args.slug) {
args.slug = slug(args.name, {
lower: true
})
}
const result = await resolve(root, args, context, info)
return result
args.slug = args.slug || await uniqueSlug(args.name, isUniqueFor(context, 'Organization'))
return resolve(root, args, context, info)
},
CreateCategory: async (resolve, root, args, context, info) => {
if (!args.slug) {
args.slug = slug(args.name, {
lower: true
})
}
const result = await resolve(root, args, context, info)
return result
args.slug = args.slug || await uniqueSlug(args.name, isUniqueFor(context, 'Category'))
return resolve(root, args, context, info)
}
}
}

View File

@ -0,0 +1,15 @@
import slugify from 'slug'
export default async function uniqueSlug (string, isUnique) {
let slug = slugify(string, {
lower: true
})
if (await isUnique(slug)) return slug
let count = 0
let uniqueSlug
do {
count += 1
uniqueSlug = `${slug}-${count}`
} while (!await isUnique(uniqueSlug))
return uniqueSlug
}

View File

@ -0,0 +1,18 @@
import uniqueSlug from './uniqueSlug'
describe('uniqueSlug', () => {
it('slugifies given string', () => {
const string = 'Hello World'
const isUnique = jest.fn()
.mockResolvedValue(true)
expect(uniqueSlug(string, isUnique)).resolves.toEqual('hello-world')
})
it('increments slugified string until unique', () => {
const string = 'Hello World'
const isUnique = jest.fn()
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
expect(uniqueSlug(string, isUnique)).resolves.toEqual('hello-world-1')
})
})

View File

@ -0,0 +1,102 @@
import Factory from '../seed/factories'
import { host, login } from '../jest/helpers'
import { GraphQLClient } from 'graphql-request'
let authenticatedClient
let headers
const factory = Factory()
beforeEach(async () => {
await factory.create('User', { email: 'user@example.org', password: '1234' })
await factory.create('User', { email: 'someone@example.org', password: '1234' })
headers = await login({ email: 'user@example.org', password: '1234' })
authenticatedClient = new GraphQLClient(host, { headers })
})
afterEach(async () => {
await factory.cleanDatabase()
})
describe('slugify', () => {
describe('CreatePost', () => {
it('generates a slug based on title', async () => {
const response = await authenticatedClient.request(`mutation {
CreatePost(
title: "I am a brand new post",
content: "Some content"
) { slug }
}`)
expect(response).toEqual({ CreatePost: { slug: 'i-am-a-brand-new-post' } })
})
describe('if slug exists', () => {
beforeEach(async () => {
const asSomeoneElse = await Factory().authenticateAs({
email: 'someone@example.org',
password: '1234'
})
await asSomeoneElse.create('Post', {
title: 'Pre-existing post',
slug: 'pre-existing-post'
})
})
it('chooses another slug', async () => {
const response = await authenticatedClient.request(`mutation {
CreatePost(
title: "Pre-existing post",
content: "Some content"
) { slug }
}`)
expect(response).toEqual({ CreatePost: { slug: 'pre-existing-post-1' } })
})
describe('but if the client specifies a slug', () => {
it('rejects CreatePost', async () => {
await expect(authenticatedClient.request(`mutation {
CreatePost(
title: "Pre-existing post",
content: "Some content",
slug: "pre-existing-post"
) { slug }
}`)
).rejects.toThrow('already exists')
})
})
})
})
describe('CreateUser', () => {
const action = async (mutation, params) => {
return authenticatedClient.request(`mutation {
${mutation}(password: "yo", ${params}) { slug }
}`)
}
it('generates a slug based on name', async () => {
await expect(action('CreateUser', 'name: "I am a user"'))
.resolves.toEqual({ CreateUser: { slug: 'i-am-a-user' } })
})
describe('if slug exists', () => {
beforeEach(async () => {
await action('CreateUser', 'name: "Pre-existing user", slug: "pre-existing-user"')
})
it('chooses another slug', async () => {
await expect(action(
'CreateUser',
'name: "pre-existing-user"'
)).resolves.toEqual({ CreateUser: { slug: 'pre-existing-user-1' } })
})
describe('but if the client specifies a slug', () => {
it('rejects CreateUser', async () => {
await expect(action(
'CreateUser',
'name: "Pre-existing user", slug: "pre-existing-user"'
)).rejects.toThrow('already exists')
})
})
})
})
})

View File

@ -1,5 +1,4 @@
import createOrUpdateLocations from './nodes/locations'
import find from 'lodash/find'
export default {
Mutation: {
@ -13,28 +12,5 @@ export default {
await createOrUpdateLocations(args.id, args.locationName, context.driver)
return result
}
},
Query: {
User: async (resolve, root, args, context, info) => {
let isIdPresent
let removeIdFromResult
try {
isIdPresent = find(info.fieldNodes[0].selectionSet.selections, item => item.name.value === 'id')
if (!isIdPresent) {
// add id to request as the user did not ask but we need it
info.fieldNodes[0].selectionSet.selections.unshift({
kind: 'Field',
name: { kind: 'Name', value: 'id' }
})
removeIdFromResult = true
}
} catch (err) {}
const result = await resolve(root, args, context, info)
if (!isIdPresent && removeIdFromResult) {
// remove id if the user did not ask for it
info.fieldNodes[0].selectionSet.selections.shift()
}
return result
}
}
}

View File

@ -24,7 +24,7 @@ function clean (dirty) {
dirty = embedToAnchor(dirty)
dirty = linkifyHtml(dirty)
dirty = sanitizeHtml(dirty, {
allowedTags: ['iframe', 'img', 'p', 'br', 'b', 'i', 'em', 'strong', 'a', 'pre', 'ul', 'li', 'ol', 's', 'strike', 'span', 'blockquote'],
allowedTags: ['iframe', 'img', 'p', 'h3', 'h4', 'br', 'hr', 'b', 'i', 'em', 'strong', 'a', 'pre', 'ul', 'li', 'ol', 's', 'strike', 'span', 'blockquote'],
allowedAttributes: {
a: ['href', 'class', 'target', 'data-*', 'contenteditable'],
span: ['contenteditable', 'class', 'data-*'],
@ -47,16 +47,22 @@ function clean (dirty) {
}
}
},
h1: 'h3',
h2: 'h3',
h3: 'h3',
h4: 'h4',
h5: 'strong',
i: 'em',
// a: function (tagName, attribs) {
// return {
// tagName: 'a',
// attribs: {
// href: attribs.href,
// target: '_blank',
// }
// }
// },
a: function (tagName, attribs) {
return {
tagName: 'a',
attribs: {
href: attribs.href,
target: '_blank',
rel: 'noopener noreferrer nofollow'
}
}
},
b: 'strong',
s: 'strike',
img: function (tagName, attribs) {
@ -92,18 +98,32 @@ function clean (dirty) {
// remove empty html tags and duplicated linebreaks and returns
dirty = dirty
// remove all tags with "space only"
.replace(/<[a-z]>[\s]*<\/[a-z]>/igm, '')
.replace(/<[a-z-]+>[\s]+<\/[a-z-]+>/gim, '')
// remove all iframes
.replace(/(<iframe(?!.*?src=(['"]).*?\2)[^>]*)(>)[^>]*\/*>/igm, '')
// replace all p tags with line breaks (and spaces) only by single linebreaks
.replace(/<p>[\s]*(<br ?\/?>)+[\s]*<\/p>/igm, '<br>')
// replace multiple linebreaks with single ones
// limit linebreaks to max 2 (equivalent to html "br" linebreak)
.replace(/(<br ?\/?>){2,}/igm, '<br>')
.replace(/[\n]{3,}/igm, '\n\n')
.replace(
/(<iframe(?!.*?src=(['"]).*?\2)[^>]*)(>)[^>]*\/*>/gim,
''
)
.replace(/[\n]{3,}/gim, '\n\n')
.replace(/(\r\n|\n\r|\r|\n)/g, '<br>$1')
// replace all p tags with line breaks (and spaces) only by single linebreaks
// limit linebreaks to max 2 (equivalent to html "br" linebreak)
.replace(/(<br ?\/?>\s*){2,}/gim, '<br>')
// remove additional linebreaks after p tags
.replace(
/<\/(p|div|th|tr)>\s*(<br ?\/?>\s*)+\s*<(p|div|th|tr)>/gim,
'</p><p>'
)
// remove additional linebreaks inside p tags
.replace(/<p><br><\/p>/g, '')
.replace(
/<[a-z-]+>(<[a-z-]+>)*\s*(<br ?\/?>\s*)+\s*(<\/[a-z-]+>)*<\/[a-z-]+>/gim,
''
)
// remove additional linebreaks when first child inside p tags
.replace(/<p>(\s*<br ?\/?>\s*)+/gim, '<p>')
// remove additional linebreaks when last child inside p tags
.replace(/(\s*<br ?\/?>\s*)+<\/p+>/gim, '</p>')
return dirty
}

View File

@ -1,12 +0,0 @@
export default function (data) {
return `
mutation {
b1: CreateBadge(id: "b1", key: "indiegogo_en_racoon", type: crowdfunding, status: permanent, icon: "/img/badges/indiegogo_en_racoon.svg") { id }
b2: CreateBadge(id: "b2", key: "indiegogo_en_rabbit", type: crowdfunding, status: permanent, icon: "/img/badges/indiegogo_en_rabbit.svg") { id }
b3: CreateBadge(id: "b3", key: "indiegogo_en_wolf", type: crowdfunding, status: permanent, icon: "/img/badges/indiegogo_en_wolf.svg") { id }
b4: CreateBadge(id: "b4", key: "indiegogo_en_bear", type: crowdfunding, status: permanent, icon: "/img/badges/indiegogo_en_bear.svg") { id }
b5: CreateBadge(id: "b5", key: "indiegogo_en_turtle", type: crowdfunding, status: permanent, icon: "/img/badges/indiegogo_en_turtle.svg") { id }
b6: CreateBadge(id: "b6", key: "indiegogo_en_rhino", type: crowdfunding, status: permanent, icon: "/img/badges/indiegogo_en_rhino.svg") { id }
}
`
}

View File

@ -1,22 +0,0 @@
export default function (data) {
return `
mutation {
cat1: CreateCategory( id: "cat1", name: "Just For Fun", slug: "justforfun", icon: "smile" ) { name }
cat2: CreateCategory( id: "cat2", name: "Happyness & Values", slug: "happyness-values", icon: "heart-o" ) { name }
cat3: CreateCategory( id: "cat3", name: "Health & Wellbeing", slug: "health-wellbeing", icon: "medkit" ) { name }
cat4: CreateCategory( id: "cat4", name: "Environment & Nature", slug: "environment-nature", icon: "tree" ) { name }
cat5: CreateCategory( id: "cat5", name: "Animal Protection", slug: "animalprotection", icon: "paw" ) { name }
cat6: CreateCategory( id: "cat6", name: "Humanrights Justice", slug: "humanrights-justice", icon: "balance-scale" ) { name }
cat7: CreateCategory( id: "cat7", name: "Education & Sciences", slug: "education-sciences", icon: "graduation-cap" ) { name }
cat8: CreateCategory( id: "cat8", name: "Cooperation & Development", slug: "cooperation-development", icon: "users" ) { name }
cat9: CreateCategory( id: "cat9", name: "Democracy & Politics", slug: "democracy-politics", icon: "university" ) { name }
cat10: CreateCategory( id: "cat10", name: "Economy & Finances", slug: "economy-finances", icon: "money" ) { name }
cat11: CreateCategory( id: "cat11", name: "Energy & Technology", slug: "energy-technology", icon: "flash" ) { name }
cat12: CreateCategory( id: "cat12", name: "IT, Internet & Data Privacy", slug: "it-internet-dataprivacy", icon: "mouse-pointer" ) { name }
cat13: CreateCategory( id: "cat13", name: "Art, Curlure & Sport", slug: "art-culture-sport", icon: "paint-brush" ) { name }
cat14: CreateCategory( id: "cat14", name: "Freedom of Speech", slug: "freedomofspeech", icon: "bullhorn" ) { name }
cat15: CreateCategory( id: "cat15", name: "Consumption & Sustainability", slug: "consumption-sustainability", icon: "shopping-cart" ) { name }
cat16: CreateCategory( id: "cat16", name: "Global Peace & Nonviolence", slug: "globalpeace-nonviolence", icon: "angellist" ) { name }
}
`
}

View File

@ -1,80 +0,0 @@
import faker from 'faker'
/**
* TODO: add a comment automatically to the correct post and relate it to the current user
*/
export default function (data) {
return `
mutation {
c1: CreateComment(
id: "c1",
content: "<p>da stimm ich dir zu. Mir ging das auch nie in den kopf, und hatte jesus nie als gott gesehen </p>"
) { id }
c1_u1: AddCommentAuthor(from: { id: "u3" }, to: { id: "c1" }) { from { id } }
c1_p1: AddCommentPost(
from: { id: "c1" },
to: { id: "p1" }
) { from { id } }
c2: CreateComment(
id: "c2",
content: "<p>Schön das es dich gibt ❤️❤️❤️❤️❤️❤️❤️❤️❤️</p>"
) { id }
c2_u1: AddCommentAuthor(from: { id: "u1" }, to: { id: "c2" }) { from { id } }
c2_p1: AddCommentPost(
from: { id: "c2" },
to: { id: "p1" }
) { from { id } }
c3: CreateComment(
id: "c3",
content: "<p>Hi Dieter,</p><p>danke für Deine Info. Hast Du mal ein Foto von Deinem Cabrio mit dem Logo drauf?</p>"
) { id }
c3_u2: AddCommentAuthor(from: { id: "u1" }, to: { id: "c3" }) { from { id } }
c3_p3: AddCommentPost(
from: { id: "c3" },
to: { id: "p3" }
) { from { id } }
c4: CreateComment(
id: "c4",
content: "<p>Das Zusammenführen aller Gruppen, die mit uns am gleichen Strang in die gleiche Richtung ziehen, in eine gemeinsame Adressenstruktur sehe ich auch als Haupt - Aufgabe für unsere neue Netzwerkbildung an.</p>"
) { id }
c4_u3: AddCommentAuthor(from: { id: "u4" }, to: { id: "c4" }) { from { id } }
c4_p2: AddCommentPost(
from: { id: "c4" },
to: { id: "p2" }
) { from { id } }
c5: CreateComment(
id: "c5",
content: "${faker.lorem.paragraph()}"
) { id }
c5_u4: AddCommentAuthor(from: { id: "u4" }, to: { id: "c5" }) { from { id } }
c5_p3: AddCommentPost(
from: { id: "c5" },
to: { id: "p3" }
) { from { id } }
c6: CreateComment(
id: "c6",
content: "${faker.lorem.paragraph()}"
) { id }
c6_u3: AddCommentAuthor(from: { id: "u3" }, to: { id: "c6" }) { from { id } }
c6_p4: AddCommentPost(
from: { id: "c6" },
to: { id: "p4" }
) { from { id } }
c7: CreateComment(
id: "c7",
content: "${faker.lorem.paragraph()}"
) { id }
c7_u2: AddCommentAuthor(from: { id: "u2" }, to: { id: "c7" }) { from { id } }
c7_p2: AddCommentPost(
from: { id: "c7" },
to: { id: "p2" }
) { from { id } }
}
`
}

View File

@ -1,43 +0,0 @@
import gql from 'graphql-tag'
import asyncForEach from '../../helpers/asyncForEach'
const seed = {
Badge: require('./badges.js').default,
Category: require('./categories.js').default,
Tags: require('./tags.js').default,
User: require('./users.js').default,
UserBadges: require('./users-badges.js').default,
UserBlacklist: require('./users-blacklist.js').default,
UserFollows: require('./users-follows.js').default,
UserFriends: require('./users-friends.js').default,
Organization: require('./organizations.js').default,
Post: require('./posts.js').default,
Comment: require('./comments.js').default,
UserShouts: require('./users-shouts.js').default
// Reports: require('./reports.js').default
}
let data = {}
export default async function (client) {
// iterate through seeds
await asyncForEach(Object.keys(seed), async key => {
const mutations = seed[key]
try {
const res = await client
.mutate({
mutation: gql(mutations(data))
})
data[key] = Object.assign(data[key] || {}, res.data)
} catch (err) {
/* eslint-disable-next-line no-console */
console.error(err)
process.exit(1)
}
})
/* eslint-disable-next-line no-console */
console.log('Seeded Data...')
}

View File

@ -1,51 +0,0 @@
export default () => {
return `mutation {
o1: CreateOrganization(
id: "o1",
name: "Democracy Deutschland",
description: "Description for democracy-deutschland.",
disabled: false,
deleted: false
) { name }
o2: CreateOrganization(
id: "o2",
name: "Human-Connection",
description: "Description for human-connection.",
disabled: false,
deleted: false
) { name }
o3: CreateOrganization(
id: "o3",
name: "Pro Veg",
description: "Description for pro-veg.",
disabled: false,
deleted: false
) { name }
o4: CreateOrganization(
id: "o4",
name: "Greenpeace",
description: "Description for greenpeace.",
disabled: false,
deleted: false
) { name }
u1_c_o1: AddOrganizationCreatedBy(
from: { id: "u1" },
to: { id: "o1" }
) { from { id } }
u1_c_o2: AddOrganizationCreatedBy(
from: { id: "u1" },
to: { id: "o2" }
) { from { id } }
u2_o_o1: AddOrganizationOwnedBy(
from: { id: "u2" },
to: { id: "o2" }
) { from { id } }
u2_c_o3: AddOrganizationOwnedBy(
from: { id: "u2" },
to: { id: "o3" }
) { from { id } }
}
`
}

View File

@ -1,112 +0,0 @@
import faker from 'faker'
export default function (data) {
return `
mutation {
p1: CreatePost(
id: "p1",
title: "Gedanken eines Polizisten zum Einsatz im Hambacher Forst",
content: "<p><strong>Diese Zukunftsstadt ist real und keine Computer-Animation</strong> sondern sie ist das Lebenswerk des mittlerweile über 100 Jahre alten Futuristen und Architekten Jacque Fresco aus Florida. In 35 Jahren (seit seinem 13. Lebensjahr) hat dieser zusammen mit seiner Frau seinen futuristischen Traum von einer besonderen Zukunftsstadt auf 85.000 Quadratmetern realisiert. In den Gebäuden und Gärten befinden sich u.a. ein Forschungszentrum, Vortragsräume und unzählige seiner Modelle &amp; Architekturentwürfe.</p><br /><p>Sein zentrales Anliegen ist eine resourcenbasierte Wirtschaft und die Abschaffung von Geld und Privatbesitz. Mit Hilfe von Roboterarbeit und dem Bedingungslosen Grundeinkommen (da nach seiner Ansicht in den kommenden Jahren fast alle Jobs automatisiert werden), möchte er eine ökologische Landwirtschaft mit Permakulturen etc. und eine effiziente Energiegewinnung (ausschließlich durch regenerative Energien) schaffen. Wenige kompatible Formen in einer sparsamen Modulbauweise (in die u.a. bereits variable Service- und Reparaturelemente integriert sind) sollen insgesamt eine soziale &amp; ökologische Utopie im Einklang mit der Natur ermöglichen.</p><br /><p>Nachfolgend der Direkt-Link auf den interessanten Artikel von Zoltan Istvan, der den Architekten und seine Frau in Florida besuchen durfte und seinen Artikel Ende 2016 auf „MOTHERBOARD“ veröffentlicht hatte:</p><br /><p>https://motherboard.vice.com/de/article/vv34nb/ich-habe-die-zukunft-besucht-in-der-wir-ohne-geld-steuern-und-besitz-leben</p><br /><p>Da soll noch jemand behaupten, es gäbe keine Utopien mehr bzw. keine Futuristen, die ihre kreativen und zukunftsfähigen Ideen (auch in ganz großem Stil) selbst in die Tat umsetzen. LG @all :)</p><br /><p><strong>Wir sind eine Menschheitsfamilie. • Wir sind eins. • Wir sind HUMAN CONNECTION</strong>❤️</p>",
image: "https://picsum.photos/1280/1024?image=352",
visibility: public,
disabled: false,
deleted: false
) { title }
p1_cat1: AddPostCategories(from: {id: "p1"}, to: {id: "cat1"}) { from { id } }
p1_cat2: AddPostCategories(from: {id: "p1"}, to: {id: "cat2"}) { from { id } }
ur1: AddUserContributions(from: { id: "u1" }, to: { id: "p1" }) { from { id } }
p1_t1: AddPostTags(
from: { id: "p1" }
to: { id: "t1" }
) { from { id } }
p1_t2: AddPostTags(
from: { id: "p1" }
to: { id: "t2" }
) { from { id } }
p1_t3: AddPostTags(
from: { id: "p1" }
to: { id: "t3" }
) { from { id } }
p2: CreatePost(
id: "p2",
title: "Julian Assange",
content: "<p><strong>Diese Zukunftsstadt ist real und keine Computer-Animation</strong> sondern sie ist das Lebenswerk des mittlerweile über 100 Jahre alten Futuristen und Architekten Jacque Fresco aus Florida. In 35 Jahren (seit seinem 13. Lebensjahr) hat dieser zusammen mit seiner Frau seinen futuristischen Traum von einer besonderen Zukunftsstadt auf 85.000 Quadratmetern realisiert. In den Gebäuden und Gärten befinden sich u.a. ein Forschungszentrum, Vortragsräume und unzählige seiner Modelle &amp; Architekturentwürfe.</p><br /><p>Sein zentrales Anliegen ist eine resourcenbasierte Wirtschaft und die Abschaffung von Geld und Privatbesitz. Mit Hilfe von Roboterarbeit und dem Bedingungslosen Grundeinkommen (da nach seiner Ansicht in den kommenden Jahren fast alle Jobs automatisiert werden), möchte er eine ökologische Landwirtschaft mit Permakulturen etc. und eine effiziente Energiegewinnung (ausschließlich durch regenerative Energien) schaffen. Wenige kompatible Formen in einer sparsamen Modulbauweise (in die u.a. bereits variable Service- und Reparaturelemente integriert sind) sollen insgesamt eine soziale &amp; ökologische Utopie im Einklang mit der Natur ermöglichen.</p><br /><p>Nachfolgend der Direkt-Link auf den interessanten Artikel von Zoltan Istvan, der den Architekten und seine Frau in Florida besuchen durfte und seinen Artikel Ende 2016 auf „MOTHERBOARD“ veröffentlicht hatte:</p><br /><p>https://motherboard.vice.com/de/article/vv34nb/ich-habe-die-zukunft-besucht-in-der-wir-ohne-geld-steuern-und-besitz-leben</p><br /><p>Da soll noch jemand behaupten, es gäbe keine Utopien mehr bzw. keine Futuristen, die ihre kreativen und zukunftsfähigen Ideen (auch in ganz großem Stil) selbst in die Tat umsetzen. LG @all :)</p><br /><p><strong>Wir sind eine Menschheitsfamilie. • Wir sind eins. • Wir sind HUMAN CONNECTION</strong>❤️</p>",
image: "https://picsum.photos/1280/1024?image=72",
visibility: public,
disabled: false,
deleted: false
) { title }
p2_cat1: AddPostCategories(from: {id: "p2"}, to: {id: "cat1"}) { from { id } }
p2_cat16: AddPostCategories(from: {id: "p2"}, to: {id: "cat16"}) { from { id } }
ur2: AddUserContributions(from: { id: "u2" }, to: { id: "p2" }) { from { id } }
p2_t4: AddPostTags(
from: { id: "p2" }
to: { id: "t4" }
) { from { id } }
p3: CreatePost(
id: "p3",
title: "Hacker, Freaks und Funktionäre...Der CCC",
content: "${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()}",
image: "https://picsum.photos/1280/1024?image=121",
visibility: public,
disabled: false,
deleted: false
) { title }
p3_cat1: AddPostCategories(from: {id: "p3"}, to: {id: "cat1"}) { from { id } }
p3_cat3: AddPostCategories(from: {id: "p3"}, to: {id: "cat3"}) { from { id } }
p3_cat14: AddPostCategories(from: {id: "p3"}, to: {id: "cat14"}) { from { id } }
ur3: AddUserContributions(from: { id: "u3" }, to: { id: "p3" }) { from { id } }
p3_t2: AddPostTags(
from: { id: "p3" }
to: { id: "t2" }
) { from { id } }
p3_t4: AddPostTags(
from: { id: "p3" }
to: { id: "t4" }
) { from { id } }
p4: CreatePost(
id: "p4",
title: "Lebensmittel (?)",
content: "${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()}",
image: "https://picsum.photos/1280/1024?image=142",
visibility: public,
disabled: false,
deleted: false
) { title }
p4_cat1: AddPostCategories(from: {id: "p4"}, to: {id: "cat1"}) { from { id } }
p4_cat9: AddPostCategories(from: {id: "p4"}, to: {id: "cat9"}) { from { id } }
p4_cat4: AddPostCategories(from: {id: "p4"}, to: {id: "cat4"}) { from { id } }
ur4: AddUserContributions(from: { id: "u4" }, to: { id: "p4" }) { from { id } }
p5: CreatePost(
id: "p5",
title: "${faker.lorem.sentence()}",
content: "${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()}",
image: "https://picsum.photos/1280/1024?image=231",
visibility: public,
disabled: false,
deleted: false
) { title }
p5_cat8: AddPostCategories(from: {id: "p5"}, to: {id: "cat8"}) { from { id } }
p5_cat12: AddPostCategories(from: {id: "p5"}, to: {id: "cat12"}) { from { id } }
ur5: AddUserContributions(from: { id: "u2" }, to: { id: "p5" }) { from { id } }
p6: CreatePost(
id: "p6",
title: "${faker.lorem.sentence()}",
content: "${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()} ${faker.lorem.sentence()}",
image: "https://picsum.photos/1280/1024?image=424",
visibility: public,
disabled: false,
deleted: false
) { title }
p6_cat1: AddPostCategories(from: {id: "p6"}, to: {id: "cat1"}) { from { id } }
p6_cat2: AddPostCategories(from: {id: "p6"}, to: {id: "cat2"}) { from { id } }
p6_cat5: AddPostCategories(from: {id: "p6"}, to: {id: "cat5"}) { from { id } }
ur6: AddUserContributions(from: { id: "u4" }, to: { id: "p6" }) { from { id } }
}
`
}

View File

@ -1,45 +0,0 @@
export default function (data) {
return `
mutation {
r1: CreateReport(id: "r1", type: contribution, description: "Bad Stuff") {
id
}
r2: CreateReport(id: "r2", type: comment, description: "Please remove this sh**") {
id
}
r3: CreateReport(id: "r3", type: user, description: "The user have misbehaved!") {
id
}
ra1: AddReportReporter(from: { id: "u1" }, to: { id: "r1" }) {
from {
id
}
}
ra2: AddReportReporter(from: { id: "u2" }, to: { id: "r2" }) {
from {
id
}
}
ra3: AddReportReporter(from: { id: "u3" }, to: { id: "r3" }) {
from {
id
}
}
rc1: AddReportContribution(from: { id: "r1" }, to: { id: "p2" }) {
from {
id
}
}
rc2: AddReportComment(from: { id: "r2" }, to: { id: "c2" }) {
from {
id
}
}
rc3: AddReportUser(from: { id: "r3" }, to: { id: "u4" }) {
from {
id
}
}
}
`
}

View File

@ -1,22 +0,0 @@
export default function (data) {
return `
mutation {
t1: CreateTag(
id: "t1",
name: "Umwelt"
) { name }
t2: CreateTag(
id: "t2",
name: "Naturschutz"
) { name }
t3: CreateTag(
id: "t3",
name: "Demokratie"
) { name }
t4: CreateTag(
id: "t4",
name: "Freiheit"
) { name }
}
`
}

View File

@ -1,12 +0,0 @@
export default function (data) {
return `
mutation {
b1_u1: AddUserBadges(from: {id: "b1"}, to: {id: "u1"}) { from { id } }
b2_u1: AddUserBadges(from: {id: "b2"}, to: {id: "u1"}) { from { id } }
b3_u1: AddUserBadges(from: {id: "b3"}, to: {id: "u1"}) { from { id } }
b6_u2: AddUserBadges(from: {id: "b6"}, to: {id: "u2"}) { from { id } }
b3_u3: AddUserBadges(from: {id: "b3"}, to: {id: "u3"}) { from { id } }
b5_u4: AddUserBadges(from: {id: "b5"}, to: {id: "u4"}) { from { id } }
}
`
}

View File

@ -1,7 +0,0 @@
export default function (data) {
return `
mutation {
u1_blacklist_u4: AddUserBlacklisted(from: { id: "u1" }, to: { id: "u4" }) { from { id } }
}
`
}

View File

@ -1,26 +0,0 @@
export default function (data) {
return `
mutation {
u1_follow_u2: AddUserFollowing(
from: { id: "u1" },
to: { id: "u2" }
) { from { id } }
u2_follow_u1: AddUserFollowing(
from: { id: "u2" },
to: { id: "u1" }
) { from { id } }
u2_follow_u3: AddUserFollowing(
from: { id: "u2" },
to: { id: "u3" }
) { from { id } }
u2_follow_u4: AddUserFollowing(
from: { id: "u2" },
to: { id: "u4" }
) { from { id } }
u4_follow_u2: AddUserFollowing(
from: { id: "u4" },
to: { id: "u2" }
) { from { id } }
}
`
}

View File

@ -1,14 +0,0 @@
export default function (data) {
return `
mutation {
u1_friends_u2: AddUserFriends(
from: { id: "u1" },
to: { id: "u2" }
) { from { id } }
u1_friends_u3: AddUserFriends(
from: { id: "u1" },
to: { id: "u3" }
) { from { id } }
}
`
}

View File

@ -1,30 +0,0 @@
export default function (data) {
return `
mutation {
u1s2: AddUserShouted(
from: { id: "u1" },
to: { id: "p2" }
) { from { id } }
u1s3: AddUserShouted(
from: { id: "u1" },
to: { id: "p3" }
) { from { id } }
u2s1: AddUserShouted(
from: { id: "u2" },
to: { id: "p1" }
) { from { id } }
u3s1: AddUserShouted(
from: { id: "u3" },
to: { id: "p1" }
) { from { id } }
u3s4: AddUserShouted(
from: { id: "u3" },
to: { id: "p4" }
) { from { id } }
u4s1: AddUserShouted(
from: { id: "u4" },
to: { id: "p1" }
) { from { id } }
}
`
}

View File

@ -1,70 +0,0 @@
import faker from 'faker'
export default function (data) {
return `
mutation {
u1: CreateUser(
id: "u1",
name: "Peter Lustig",
password: "1234",
email: "admin@example.org",
avatar: "${faker.internet.avatar()}",
locationName: "Hamburg, Germany",
role: admin,
disabled: false,
deleted: false) {
id
name
email
avatar
role
}
u2: CreateUser(
id: "u2",
name: "Bob der Bausmeister",
password: "1234",
email: "moderator@example.org",
avatar: "${faker.internet.avatar()}",
locationName: "USA",
role: moderator,
disabled: false,
deleted: false) {
id
name
email
avatar
role
}
u3: CreateUser(
id: "u3",
name: "Jenny Rostock",
password: "1234",
email: "user@example.org",
avatar: "${faker.internet.avatar()}",
role: user,
disabled: false,
deleted: false) {
id
name
email
avatar
role
}
u4: CreateUser(
id: "u4",
name: "Angie Banjie",
password: "1234",
email: "angie@example.org",
avatar: "${faker.internet.avatar()}",
role: user,
disabled: false,
deleted: false) {
id
name
email
avatar
role
}
}
`
}

View File

@ -23,15 +23,3 @@ export default function (params) {
}
`
}
export function relate (type, params) {
const { from, to } = params
return `
mutation {
${from}_${type}_${to}: AddComment${type}(
from: { id: "${from}" },
to: { id: "${to}" }
) { from { id } }
}
`
}

View File

@ -1,6 +1,15 @@
import { GraphQLClient, request } from 'graphql-request'
import { getDriver } from '../../bootstrap/neo4j'
import createBadge from './badges.js'
import createUser from './users.js'
import createOrganization from './organizations.js'
import createPost from './posts.js'
import createComment from './comments.js'
import createCategory from './categories.js'
import createTag from './tags.js'
import createReport from './reports.js'
export const seedServerHost = 'http://127.0.0.1:4001'
const authenticatedHeaders = async ({ email, password }, host) => {
@ -15,35 +24,15 @@ const authenticatedHeaders = async ({ email, password }, host) => {
authorization: `Bearer ${response.login.token}`
}
}
const factories = {
'badge': require('./badges.js').default,
'user': require('./users.js').default,
'organization': require('./organizations.js').default,
'post': require('./posts.js').default,
'comment': require('./comments.js').default,
'category': require('./categories.js').default,
'tag': require('./tags.js').default,
'report': require('./reports.js').default
}
const relationFactories = {
'user': require('./users.js').relate,
'organization': require('./organizations.js').relate,
'post': require('./posts.js').relate,
'comment': require('./comments.js').relate
}
export const create = (model, parameters, options) => {
const graphQLClient = new GraphQLClient(seedServerHost, options)
const mutation = factories[model](parameters)
return graphQLClient.request(mutation)
}
export const relate = (model, type, parameters, options) => {
const graphQLClient = new GraphQLClient(seedServerHost, options)
const mutation = relationFactories[model](type, parameters)
return graphQLClient.request(mutation)
'Badge': createBadge,
'User': createUser,
'Organization': createOrganization,
'Post': createPost,
'Comment': createComment,
'Category': createCategory,
'Tag': createTag,
'Report': createReport
}
export const cleanDatabase = async (options = {}) => {
@ -73,6 +62,7 @@ export default function Factory (options = {}) {
neo4jDriver,
seedServerHost,
graphQLClient,
factories,
lastResponse: null,
async authenticateAs ({ email, password }) {
const headers = await authenticatedHeaders({ email, password }, seedServerHost)
@ -81,12 +71,20 @@ export default function Factory (options = {}) {
return this
},
async create (node, properties) {
const mutation = factories[node](properties)
const mutation = this.factories[node](properties)
this.lastResponse = await this.graphQLClient.request(mutation)
return this
},
async relate (node, relationship, properties) {
const mutation = relationFactories[node](relationship, properties)
const { from, to } = properties
const mutation = `
mutation {
Add${node}${relationship}(
from: { id: "${from}" },
to: { id: "${to}" }
) { from { id } }
}
`
this.lastResponse = await this.graphQLClient.request(mutation)
return this
},

View File

@ -22,15 +22,3 @@ export default function create (params) {
}
`
}
export function relate (type, params) {
const { from, to } = params
return `
mutation {
${from}_${type}_${to}: AddOrganization${type}(
from: { id: "${from}" },
to: { id: "${to}" }
) { from { id } }
}
`
}

View File

@ -32,15 +32,3 @@ export default function (params) {
}
`
}
export function relate (type, params) {
const { from, to } = params
return `
mutation {
${from}_${type}_${to}: AddPost${type}(
from: { id: "${from}" },
to: { id: "${to}" }
) { from { id } }
}
`
}

View File

@ -33,15 +33,3 @@ export default function create (params) {
}
`
}
export function relate (type, params) {
const { from, to } = params
return `
mutation {
${from}_${type}_${to}: AddUser${type}(
from: { id: "${from}" },
to: { id: "${to}" }
) { from { id } }
}
`
}

View File

@ -1,19 +1,199 @@
import ApolloClient from 'apollo-client'
import dotenv from 'dotenv'
import fetch from 'node-fetch'
import { HttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import Seed from './data/index'
import Factory from './factories'
dotenv.config()
/* eslint-disable no-multi-spaces */
(async function () {
try {
const f = Factory()
await Promise.all([
f.create('Badge', { id: 'b1', key: 'indiegogo_en_racoon', type: 'crowdfunding', status: 'permanent', icon: '/img/badges/indiegogo_en_racoon.svg' }),
f.create('Badge', { id: 'b2', key: 'indiegogo_en_rabbit', type: 'crowdfunding', status: 'permanent', icon: '/img/badges/indiegogo_en_rabbit.svg' }),
f.create('Badge', { id: 'b3', key: 'indiegogo_en_wolf', type: 'crowdfunding', status: 'permanent', icon: '/img/badges/indiegogo_en_wolf.svg' }),
f.create('Badge', { id: 'b4', key: 'indiegogo_en_bear', type: 'crowdfunding', status: 'permanent', icon: '/img/badges/indiegogo_en_bear.svg' }),
f.create('Badge', { id: 'b5', key: 'indiegogo_en_turtle', type: 'crowdfunding', status: 'permanent', icon: '/img/badges/indiegogo_en_turtle.svg' }),
f.create('Badge', { id: 'b6', key: 'indiegogo_en_rhino', type: 'crowdfunding', status: 'permanent', icon: '/img/badges/indiegogo_en_rhino.svg' })
])
if (process.env.NODE_ENV === 'production') {
throw new Error('YOU CAN`T SEED IN PRODUCTION MODE')
}
await Promise.all([
f.create('User', { id: 'u1', name: 'Peter Lustig', role: 'admin', email: 'admin@example.org' }),
f.create('User', { id: 'u2', name: 'Bob der Baumeister', role: 'moderator', email: 'moderator@example.org' }),
f.create('User', { id: 'u3', name: 'Jenny Rostock', role: 'user', email: 'user@example.org' }),
f.create('User', { id: 'u4', name: 'Tick', role: 'user', email: 'tick@example.org' }),
f.create('User', { id: 'u5', name: 'Trick', role: 'user', email: 'trick@example.org' }),
f.create('User', { id: 'u6', name: 'Track', role: 'user', email: 'track@example.org' }),
f.create('User', { id: 'u7', name: 'Dagobert', role: 'user', email: 'dagobert@example.org' })
])
const client = new ApolloClient({
link: new HttpLink({ uri: process.env.GRAPHQL_URI, fetch }),
cache: new InMemoryCache()
})
await Promise.all([
f.relate('User', 'Badges', { from: 'b6', to: 'u1' }),
f.relate('User', 'Badges', { from: 'b5', to: 'u2' }),
f.relate('User', 'Badges', { from: 'b4', to: 'u3' }),
f.relate('User', 'Badges', { from: 'b3', to: 'u4' }),
f.relate('User', 'Badges', { from: 'b2', to: 'u5' }),
f.relate('User', 'Badges', { from: 'b1', to: 'u6' }),
f.relate('User', 'Following', { from: 'u1', to: 'u2' }),
f.relate('User', 'Following', { from: 'u2', to: 'u3' }),
f.relate('User', 'Following', { from: 'u3', to: 'u4' }),
f.relate('User', 'Following', { from: 'u4', to: 'u5' }),
f.relate('User', 'Following', { from: 'u5', to: 'u6' }),
f.relate('User', 'Following', { from: 'u6', to: 'u7' }),
f.relate('User', 'Friends', { from: 'u1', to: 'u2' }),
f.relate('User', 'Friends', { from: 'u1', to: 'u3' }),
f.relate('User', 'Friends', { from: 'u2', to: 'u3' }),
f.relate('User', 'Blacklisted', { from: 'u7', to: 'u4' }),
f.relate('User', 'Blacklisted', { from: 'u7', to: 'u5' }),
f.relate('User', 'Blacklisted', { from: 'u7', to: 'u6' })
])
Seed(client)
await Promise.all([
f.create('Category', { id: 'cat1', name: 'Just For Fun', slug: 'justforfun', icon: 'smile' }),
f.create('Category', { id: 'cat2', name: 'Happyness & Values', slug: 'happyness-values', icon: 'heart-o' }),
f.create('Category', { id: 'cat3', name: 'Health & Wellbeing', slug: 'health-wellbeing', icon: 'medkit' }),
f.create('Category', { id: 'cat4', name: 'Environment & Nature', slug: 'environment-nature', icon: 'tree' }),
f.create('Category', { id: 'cat5', name: 'Animal Protection', slug: 'animalprotection', icon: 'paw' }),
f.create('Category', { id: 'cat6', name: 'Humanrights Justice', slug: 'humanrights-justice', icon: 'balance-scale' }),
f.create('Category', { id: 'cat7', name: 'Education & Sciences', slug: 'education-sciences', icon: 'graduation-cap' }),
f.create('Category', { id: 'cat8', name: 'Cooperation & Development', slug: 'cooperation-development', icon: 'users' }),
f.create('Category', { id: 'cat9', name: 'Democracy & Politics', slug: 'democracy-politics', icon: 'university' }),
f.create('Category', { id: 'cat10', name: 'Economy & Finances', slug: 'economy-finances', icon: 'money' }),
f.create('Category', { id: 'cat11', name: 'Energy & Technology', slug: 'energy-technology', icon: 'flash' }),
f.create('Category', { id: 'cat12', name: 'IT, Internet & Data Privacy', slug: 'it-internet-dataprivacy', icon: 'mouse-pointer' }),
f.create('Category', { id: 'cat13', name: 'Art, Curlure & Sport', slug: 'art-culture-sport', icon: 'paint-brush' }),
f.create('Category', { id: 'cat14', name: 'Freedom of Speech', slug: 'freedomofspeech', icon: 'bullhorn' }),
f.create('Category', { id: 'cat15', name: 'Consumption & Sustainability', slug: 'consumption-sustainability', icon: 'shopping-cart' }),
f.create('Category', { id: 'cat16', name: 'Global Peace & Nonviolence', slug: 'globalpeace-nonviolence', icon: 'angellist' })
])
await Promise.all([
f.create('Tag', { id: 't1', name: 'Umwelt' }),
f.create('Tag', { id: 't2', name: 'Naturschutz' }),
f.create('Tag', { id: 't3', name: 'Demokratie' }),
f.create('Tag', { id: 't4', name: 'Freiheit' })
])
const [ asAdmin, asModerator, asUser, asTick, asTrick, asTrack ] = await Promise.all([
Factory().authenticateAs({ email: 'admin@example.org', password: '1234' }),
Factory().authenticateAs({ email: 'moderator@example.org', password: '1234' }),
Factory().authenticateAs({ email: 'user@example.org', password: '1234' }),
Factory().authenticateAs({ email: 'tick@example.org', password: '1234' }),
Factory().authenticateAs({ email: 'trick@example.org', password: '1234' }),
Factory().authenticateAs({ email: 'track@example.org', password: '1234' })
])
await Promise.all([
asAdmin.create('Post', { id: 'p0' }),
asModerator.create('Post', { id: 'p1' }),
asUser.create('Post', { id: 'p2' }),
asTick.create('Post', { id: 'p3' }),
asTrick.create('Post', { id: 'p4' }),
asTrack.create('Post', { id: 'p5' }),
asAdmin.create('Post', { id: 'p6' }),
asModerator.create('Post', { id: 'p7' }),
asUser.create('Post', { id: 'p8' }),
asTick.create('Post', { id: 'p9' }),
asTrick.create('Post', { id: 'p10' }),
asTrack.create('Post', { id: 'p11' }),
asAdmin.create('Post', { id: 'p12' }),
asModerator.create('Post', { id: 'p13' }),
asUser.create('Post', { id: 'p14' }),
asTick.create('Post', { id: 'p15' })
])
await Promise.all([
f.relate('Post', 'Categories', { from: 'p0', to: 'cat16' }),
f.relate('Post', 'Categories', { from: 'p1', to: 'cat1' }),
f.relate('Post', 'Categories', { from: 'p2', to: 'cat2' }),
f.relate('Post', 'Categories', { from: 'p3', to: 'cat3' }),
f.relate('Post', 'Categories', { from: 'p4', to: 'cat4' }),
f.relate('Post', 'Categories', { from: 'p5', to: 'cat5' }),
f.relate('Post', 'Categories', { from: 'p6', to: 'cat6' }),
f.relate('Post', 'Categories', { from: 'p7', to: 'cat7' }),
f.relate('Post', 'Categories', { from: 'p8', to: 'cat8' }),
f.relate('Post', 'Categories', { from: 'p9', to: 'cat9' }),
f.relate('Post', 'Categories', { from: 'p10', to: 'cat10' }),
f.relate('Post', 'Categories', { from: 'p11', to: 'cat11' }),
f.relate('Post', 'Categories', { from: 'p12', to: 'cat12' }),
f.relate('Post', 'Categories', { from: 'p13', to: 'cat13' }),
f.relate('Post', 'Categories', { from: 'p14', to: 'cat14' }),
f.relate('Post', 'Categories', { from: 'p15', to: 'cat15' }),
f.relate('Post', 'Tags', { from: 'p0', to: 't4' }),
f.relate('Post', 'Tags', { from: 'p1', to: 't1' }),
f.relate('Post', 'Tags', { from: 'p2', to: 't2' }),
f.relate('Post', 'Tags', { from: 'p3', to: 't3' }),
f.relate('Post', 'Tags', { from: 'p4', to: 't4' }),
f.relate('Post', 'Tags', { from: 'p5', to: 't1' }),
f.relate('Post', 'Tags', { from: 'p6', to: 't2' }),
f.relate('Post', 'Tags', { from: 'p7', to: 't3' }),
f.relate('Post', 'Tags', { from: 'p8', to: 't4' }),
f.relate('Post', 'Tags', { from: 'p9', to: 't1' }),
f.relate('Post', 'Tags', { from: 'p10', to: 't2' }),
f.relate('Post', 'Tags', { from: 'p11', to: 't3' }),
f.relate('Post', 'Tags', { from: 'p12', to: 't4' }),
f.relate('Post', 'Tags', { from: 'p13', to: 't1' }),
f.relate('Post', 'Tags', { from: 'p14', to: 't2' }),
f.relate('Post', 'Tags', { from: 'p15', to: 't3' })
])
await Promise.all([
f.relate('User', 'Shouted', { from: 'u1', to: 'p2' }),
f.relate('User', 'Shouted', { from: 'u1', to: 'p3' }),
f.relate('User', 'Shouted', { from: 'u2', to: 'p1' }),
f.relate('User', 'Shouted', { from: 'u3', to: 'p1' }),
f.relate('User', 'Shouted', { from: 'u3', to: 'p4' }),
f.relate('User', 'Shouted', { from: 'u4', to: 'p1' })
])
await Promise.all([
f.create('Comment', { id: 'c1' }),
f.create('Comment', { id: 'c2' }),
f.create('Comment', { id: 'c3' }),
f.create('Comment', { id: 'c4' }),
f.create('Comment', { id: 'c5' }),
f.create('Comment', { id: 'c6' }),
f.create('Comment', { id: 'c7' })
])
await Promise.all([
f.relate('Comment', 'Author', { from: 'u3', to: 'c1' }),
f.relate('Comment', 'Post', { from: 'c1', to: 'p1' }),
f.relate('Comment', 'Author', { from: 'u1', to: 'c2' }),
f.relate('Comment', 'Post', { from: 'c2', to: 'p1' }),
f.relate('Comment', 'Author', { from: 'u1', to: 'c3' }),
f.relate('Comment', 'Post', { from: 'c3', to: 'p3' }),
f.relate('Comment', 'Author', { from: 'u4', to: 'c4' }),
f.relate('Comment', 'Post', { from: 'c4', to: 'p2' }),
f.relate('Comment', 'Author', { from: 'u4', to: 'c5' }),
f.relate('Comment', 'Post', { from: 'c5', to: 'p3' }),
f.relate('Comment', 'Author', { from: 'u3', to: 'c6' }),
f.relate('Comment', 'Post', { from: 'c6', to: 'p4' }),
f.relate('Comment', 'Author', { from: 'u2', to: 'c7' }),
f.relate('Comment', 'Post', { from: 'c7', to: 'p2' })
])
await Promise.all([
asTick.create('Report', { description: 'I don\'t like this comment', resource: { id: 'c1', type: 'comment' } }),
asTrick.create('Report', { description: 'I don\'t like this post', resource: { id: 'p1', type: 'contribution' } }),
asTrack.create('Report', { description: 'I don\'t like this user', resource: { id: 'u1', type: 'user' } })
])
await Promise.all([
f.create('Organization', { id: 'o1', name: 'Democracy Deutschland', description: 'Description for democracy-deutschland.' }),
f.create('Organization', { id: 'o2', name: 'Human-Connection', description: 'Description for human-connection.' }),
f.create('Organization', { id: 'o3', name: 'Pro Veg', description: 'Description for pro-veg.' }),
f.create('Organization', { id: 'o4', name: 'Greenpeace', description: 'Description for greenpeace.' })
])
await Promise.all([
f.relate('Organization', 'CreatedBy', { from: 'u1', to: 'o1' }),
f.relate('Organization', 'CreatedBy', { from: 'u1', to: 'o2' }),
f.relate('Organization', 'OwnedBy', { from: 'u2', to: 'o2' }),
f.relate('Organization', 'OwnedBy', { from: 'u2', to: 'o3' })
])
/* eslint-disable-next-line no-console */
console.log('Seeded Data...')
} catch (err) {
/* eslint-disable-next-line no-console */
console.error(err)
process.exit(1)
}
})()
/* eslint-enable no-multi-spaces */