Merge branch 'master' of github.com:Human-Connection/Human-Connection into 1709-send-feedbacks-in-report-processes-second-approach

# Conflicts:
#	backend/src/db/seed.js
#	backend/src/middleware/notifications/notificationsMiddleware.js
#	backend/src/schema/resolvers/notifications.js
#	webapp/components/NotificationsTable/NotificationsTable.spec.js
This commit is contained in:
Wolfgang Huß 2020-04-01 12:22:56 +02:00
commit a52cbe1c66
276 changed files with 6955 additions and 4391 deletions

View File

@ -1,5 +1,10 @@
dist: xenial
language: generic
language: node_js
node_js: lts/*
cache:
yarn: false
npm: false
addons:
apt:
packages:
@ -7,11 +12,11 @@ addons:
snaps:
- docker
firefox: "latest-esr"
install:
- yarn global add wait-on
# Install Codecov
- yarn install
- yarn install --frozen-lockfile
- cp backend/.env.template backend/.env
before_script:

View File

@ -4,6 +4,87 @@ All notable changes to this project will be documented in this file. Dates are d
Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
#### [v0.6.0](https://github.com/Human-Connection/Human-Connection/compare/v0.4.2...v0.6.0)
> 27 March 2020
- refactor: FilterMenu as a first step to remove ds-flex [`#3257`](https://github.com/Human-Connection/Human-Connection/pull/3257)
- build(deps): bump date-fns from 2.11.0 to 2.11.1 in /webapp [`#3355`](https://github.com/Human-Connection/Human-Connection/pull/3355)
- Remove dangling image urls [`#3343`](https://github.com/Human-Connection/Human-Connection/pull/3343)
- build(deps-dev): bump expect from 25.2.0 to 25.2.3 [`#3347`](https://github.com/Human-Connection/Human-Connection/pull/3347)
- build(deps-dev): bump babel-jest from 25.2.1 to 25.2.3 in /backend [`#3350`](https://github.com/Human-Connection/Human-Connection/pull/3350)
- build(deps-dev): bump babel-jest from 25.2.0 to 25.2.3 in /webapp [`#3353`](https://github.com/Human-Connection/Human-Connection/pull/3353)
- build(deps): bump date-fns from 2.11.0 to 2.11.1 in /backend [`#3351`](https://github.com/Human-Connection/Human-Connection/pull/3351)
- build(deps): bump @sentry/node from 5.15.0 to 5.15.2 in /backend [`#3348`](https://github.com/Human-Connection/Human-Connection/pull/3348)
- build(deps-dev): bump jest from 25.2.0 to 25.2.3 in /backend [`#3346`](https://github.com/Human-Connection/Human-Connection/pull/3346)
- build(deps-dev): bump date-fns from 2.11.0 to 2.11.1 [`#3345`](https://github.com/Human-Connection/Human-Connection/pull/3345)
- build(deps-dev): bump @babel/preset-env from 7.8.7 to 7.9.0 [`#3309`](https://github.com/Human-Connection/Human-Connection/pull/3309)
- build(deps-dev): bump @babel/preset-env from 7.8.7 to 7.9.0 in /backend [`#3314`](https://github.com/Human-Connection/Human-Connection/pull/3314)
- build(deps-dev): bump babel-jest from 25.2.0 to 25.2.1 in /backend [`#3341`](https://github.com/Human-Connection/Human-Connection/pull/3341)
- build(deps-dev): bump jest from 25.1.0 to 25.2.1 in /webapp [`#3342`](https://github.com/Human-Connection/Human-Connection/pull/3342)
- feat(backend): upload original image files on S3 object storage [`#3262`](https://github.com/Human-Connection/Human-Connection/pull/3262)
- build(deps-dev): bump babel-jest from 25.1.0 to 25.2.0 in /backend [`#3336`](https://github.com/Human-Connection/Human-Connection/pull/3336)
- build(deps): bump nuxt from 2.12.0 to 2.12.1 in /webapp [`#3338`](https://github.com/Human-Connection/Human-Connection/pull/3338)
- build(deps-dev): bump babel-jest from 25.1.0 to 25.2.0 in /webapp [`#3340`](https://github.com/Human-Connection/Human-Connection/pull/3340)
- build(deps-dev): bump jest from 25.1.0 to 25.2.0 in /backend [`#3335`](https://github.com/Human-Connection/Human-Connection/pull/3335)
- build(deps-dev): bump expect from 25.1.0 to 25.2.0 [`#3333`](https://github.com/Human-Connection/Human-Connection/pull/3333)
- build(deps): bump @nuxtjs/sentry from 3.3.1 to 4.0.0 in /webapp [`#3332`](https://github.com/Human-Connection/Human-Connection/pull/3332)
- build(deps-dev): bump @babel/core from 7.8.7 to 7.9.0 in /webapp [`#3316`](https://github.com/Human-Connection/Human-Connection/pull/3316)
- build(deps-dev): bump @babel/core from 7.8.7 to 7.9.0 in /backend [`#3313`](https://github.com/Human-Connection/Human-Connection/pull/3313)
- build(deps-dev): bump @babel/preset-env from 7.8.7 to 7.9.0 in /webapp [`#3319`](https://github.com/Human-Connection/Human-Connection/pull/3319)
- build(deps-dev): bump @babel/register from 7.8.6 to 7.9.0 in /backend [`#3305`](https://github.com/Human-Connection/Human-Connection/pull/3305)
- build(deps): bump @sentry/node from 5.14.2 to 5.15.0 in /backend [`#3331`](https://github.com/Human-Connection/Human-Connection/pull/3331)
- build(deps-dev): bump prettier from 1.19.1 to 2.0.2 in /webapp [`#3327`](https://github.com/Human-Connection/Human-Connection/pull/3327)
- build(deps-dev): bump babel-loader from 8.0.6 to 8.1.0 in /webapp [`#3315`](https://github.com/Human-Connection/Human-Connection/pull/3315)
- build(deps-dev): bump @babel/register from 7.8.6 to 7.9.0 [`#3310`](https://github.com/Human-Connection/Human-Connection/pull/3310)
- build(deps-dev): bump @babel/core from 7.8.7 to 7.9.0 [`#3304`](https://github.com/Human-Connection/Human-Connection/pull/3304)
- fix(migration): return null for Image.url [`#3323`](https://github.com/Human-Connection/Human-Connection/pull/3323)
- build(deps): bump graphql-shield from 7.2.0 to 7.2.1 in /backend [`#3296`](https://github.com/Human-Connection/Human-Connection/pull/3296)
- fix(build): make locations spec more resilient [`#3324`](https://github.com/Human-Connection/Human-Connection/pull/3324)
- fix(migration): Avoid unique constraint violation [`#3303`](https://github.com/Human-Connection/Human-Connection/pull/3303)
- chore: upgrade to v0.5.0 [`#3302`](https://github.com/Human-Connection/Human-Connection/pull/3302)
- build(deps): bump validator from 12.2.0 to 13.0.0 in /webapp [`#3301`](https://github.com/Human-Connection/Human-Connection/pull/3301)
- feat: Search for Hashtags [`#3297`](https://github.com/Human-Connection/Human-Connection/pull/3297)
- build(deps): bump metascraper-soundcloud from 5.11.6 to 5.11.7 in /backend [`#3300`](https://github.com/Human-Connection/Human-Connection/pull/3300)
- build(deps): bump validator from 12.2.0 to 13.0.0 in /backend [`#3299`](https://github.com/Human-Connection/Human-Connection/pull/3299)
- build(deps-dev): bump @storybook/addon-a11y from 5.3.14 to 5.3.17 in /webapp [`#3283`](https://github.com/Human-Connection/Human-Connection/pull/3283)
- build(deps-dev): bump cross-env from 6.0.3 to 7.0.2 [`#3294`](https://github.com/Human-Connection/Human-Connection/pull/3294)
- build(deps-dev): bump @storybook/vue from 5.3.14 to 5.3.17 in /webapp [`#3285`](https://github.com/Human-Connection/Human-Connection/pull/3285)
- build(deps): bump graphql-shield from 7.0.14 to 7.2.0 in /backend [`#3288`](https://github.com/Human-Connection/Human-Connection/pull/3288)
- build(deps): bump nuxt from 2.11.0 to 2.12.0 in /webapp [`#3291`](https://github.com/Human-Connection/Human-Connection/pull/3291)
- build(deps): bump cookie-universal-nuxt from 2.1.2 to 2.1.3 in /webapp [`#3289`](https://github.com/Human-Connection/Human-Connection/pull/3289)
- feat: Specs For Searches [`#3199`](https://github.com/Human-Connection/Human-Connection/pull/3199)
- chore(ci): Follow cypress docs to cache libraries [`#3292`](https://github.com/Human-Connection/Human-Connection/pull/3292)
- build(deps-dev): bump cypress from 4.1.0 to 4.2.0 [`#3287`](https://github.com/Human-Connection/Human-Connection/pull/3287)
- build(deps): [security] bump acorn from 5.7.3 to 5.7.4 in /webapp [`#3268`](https://github.com/Human-Connection/Human-Connection/pull/3268)
- feat: Introduce graphql image type [`#3043`](https://github.com/Human-Connection/Human-Connection/pull/3043)
- build(deps-dev): bump @storybook/addon-actions from 5.3.14 to 5.3.17 in /webapp [`#3284`](https://github.com/Human-Connection/Human-Connection/pull/3284)
- build(deps): bump date-fns from 2.10.0 to 2.11.0 in /webapp [`#3281`](https://github.com/Human-Connection/Human-Connection/pull/3281)
- chore: Dockerfile/Travis node versions match [`#3267`](https://github.com/Human-Connection/Human-Connection/pull/3267)
- build(deps): bump date-fns from 2.10.0 to 2.11.0 in /backend [`#3278`](https://github.com/Human-Connection/Human-Connection/pull/3278)
- build(deps): bump @hapi/joi from 17.1.0 to 17.1.1 in /backend [`#3277`](https://github.com/Human-Connection/Human-Connection/pull/3277)
- build(deps): bump neo4j-driver from 4.0.1 to 4.0.2 in /backend [`#3276`](https://github.com/Human-Connection/Human-Connection/pull/3276)
- build(deps-dev): bump neo4j-driver from 4.0.1 to 4.0.2 [`#3275`](https://github.com/Human-Connection/Human-Connection/pull/3275)
- refactor: deprecated slot syntax [2117] [`#3258`](https://github.com/Human-Connection/Human-Connection/pull/3258)
- build(deps-dev): bump @storybook/addon-notes from 5.3.14 to 5.3.17 in /webapp [`#3282`](https://github.com/Human-Connection/Human-Connection/pull/3282)
- build(deps): bump mustache from 4.0.0 to 4.0.1 in /backend [`#3280`](https://github.com/Human-Connection/Human-Connection/pull/3280)
- build(deps): bump @sentry/node from 5.14.1 to 5.14.2 in /backend [`#3274`](https://github.com/Human-Connection/Human-Connection/pull/3274)
- build(deps-dev): bump date-fns from 2.10.0 to 2.11.0 [`#3273`](https://github.com/Human-Connection/Human-Connection/pull/3273)
- build(deps): [security] bump acorn from 6.3.0 to 6.4.1 in /backend [`#3270`](https://github.com/Human-Connection/Human-Connection/pull/3270)
- build(deps): [security] bump acorn from 6.1.1 to 6.4.1 [`#3269`](https://github.com/Human-Connection/Human-Connection/pull/3269)
- build(deps): bump graphql-shield from 7.1.0 to 7.2.0 in /backend [`#3265`](https://github.com/Human-Connection/Human-Connection/pull/3265)
- build(deps): bump sanitize-html from 1.22.0 to 1.22.1 in /backend [`#3264`](https://github.com/Human-Connection/Human-Connection/pull/3264)
- build(deps): bump @sentry/node from 5.14.0 to 5.14.1 in /backend [`#3263`](https://github.com/Human-Connection/Human-Connection/pull/3263)
- build(deps-dev): bump @vue/server-test-utils from 1.0.0-beta.31 to 1.0.0-beta.32 in /webapp [`#3249`](https://github.com/Human-Connection/Human-Connection/pull/3249)
- build(deps-dev): bump @babel/preset-env from 7.8.6 to 7.8.7 in /webapp [`#3215`](https://github.com/Human-Connection/Human-Connection/pull/3215)
- build(deps-dev): bump fuse.js from 3.4.6 to 3.6.1 in /webapp [`#3239`](https://github.com/Human-Connection/Human-Connection/pull/3239)
- build(deps): bump @nuxtjs/sentry from 3.2.4 to 3.3.1 in /webapp [`#3237`](https://github.com/Human-Connection/Human-Connection/pull/3237)
- build(deps-dev): bump eslint-plugin-jest from 23.8.1 to 23.8.2 in /webapp [`#3228`](https://github.com/Human-Connection/Human-Connection/pull/3228)
- chore: Update to version 0.4.2 [`#3261`](https://github.com/Human-Connection/Human-Connection/pull/3261)
- Update prettier to v2 [`276ea79`](https://github.com/Human-Connection/Human-Connection/commit/276ea79e8ff2de2d02698b486671aee7cfda860e)
- refactor: CategoriesFilter to not use ds-flex [`1ffde6b`](https://github.com/Human-Connection/Human-Connection/commit/1ffde6bf1034d1a1d9b7bca62fe66fe64527314c)
- Changes requested by @mattwr18 [`9c08db2`](https://github.com/Human-Connection/Human-Connection/commit/9c08db22dcd0ca1ad6e59be8fb0f287935b45537)
#### [v0.4.2](https://github.com/Human-Connection/Human-Connection/compare/v0.4.1...v0.4.2)
> 12 March 2020
@ -230,7 +311,7 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
- refactor TeaserImage component [`e14cbf8`](https://github.com/Human-Connection/Human-Connection/commit/e14cbf8173e3040b5285ba6a5c73e2d2d2a47860)
- refactor DeleteData template and CSS [`509892b`](https://github.com/Human-Connection/Human-Connection/commit/509892b6caee6c4ca8384fb0090122ced98edfd4)
#### [v0.3.0](https://github.com/Human-Connection/Human-Connection/compare/v0.2.1...v0.3.0)
#### [v0.3.0](https://github.com/Human-Connection/Human-Connection/compare/0.2.2...v0.3.0)
> 31 January 2020
@ -298,6 +379,15 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
- build(deps-dev): bump jest from 24.9.0 to 25.1.0 in /backend [`#2862`](https://github.com/Human-Connection/Human-Connection/pull/2862)
- docs(deployment): Explain how to setup metrics [`#2825`](https://github.com/Human-Connection/Human-Connection/pull/2825)
- refactor(styleguide): Migrate Avatar component to monorepo [`#2700`](https://github.com/Human-Connection/Human-Connection/pull/2700)
- docs(deployment): Explain how to setup metrics (#2825) [`#2411`](https://github.com/Human-Connection/Human-Connection/issues/2411) [`#2777`](https://github.com/Human-Connection/Human-Connection/issues/2777)
- Get rid of different factory files [`fc36729`](https://github.com/Human-Connection/Human-Connection/commit/fc367297e3e054f09b7f8f31788ab68d87f6babf)
- Refactor factory for comments [`2fc71d7`](https://github.com/Human-Connection/Human-Connection/commit/2fc71d75a5d5eab9c3467e94e00257ef6dd7d8a0)
- Refactor user factory [`2a79c53`](https://github.com/Human-Connection/Human-Connection/commit/2a79c53765b73f9b91691eb75f55cf8c9e48306e)
#### [0.2.2](https://github.com/Human-Connection/Human-Connection/compare/0.2.1...0.2.2)
> 21 January 2020
- feat: Convert block/unblock to mute/unmute [`#2686`](https://github.com/Human-Connection/Human-Connection/pull/2686)
- removed obsolete German keys [`#2845`](https://github.com/Human-Connection/Human-Connection/pull/2845)
- build(deps-dev): bump @vue/server-test-utils in /webapp [`#2852`](https://github.com/Human-Connection/Human-Connection/pull/2852)
@ -318,6 +408,14 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
- build(deps): bump metascraper-title from 5.10.3 to 5.10.5 in /backend [`#2835`](https://github.com/Human-Connection/Human-Connection/pull/2835)
- build(deps): bump metascraper-publisher in /backend [`#2836`](https://github.com/Human-Connection/Human-Connection/pull/2836)
- build(deps): bump metascraper-audio from 5.10.3 to 5.10.5 in /backend [`#2840`](https://github.com/Human-Connection/Human-Connection/pull/2840)
- Generate changelog with auto-changelog [`02367f9`](https://github.com/Human-Connection/Human-Connection/commit/02367f93e0ad635d5f43adf01695f85f06f4c0d2)
- clean up UserAvatar a little [`d20421c`](https://github.com/Human-Connection/Human-Connection/commit/d20421cb70c4bda51fdaf59f28c3a060b59bb0cd)
- display username below slug when there is no date-time [`e93332b`](https://github.com/Human-Connection/Human-Connection/commit/e93332b17361d2c59a841e7c03e93647ec76918f)
#### [0.2.1](https://github.com/Human-Connection/Human-Connection/compare/v0.2.1...0.2.1)
> 20 January 2020
- build(deps): bump metascraper-author from 5.10.3 to 5.10.5 in /backend [`#2838`](https://github.com/Human-Connection/Human-Connection/pull/2838)
- build(deps): bump metascraper-url from 5.10.3 to 5.10.5 in /backend [`#2832`](https://github.com/Human-Connection/Human-Connection/pull/2832)
- build(deps): bump metascraper-lang from 5.10.3 to 5.10.5 in /backend [`#2831`](https://github.com/Human-Connection/Human-Connection/pull/2831)
@ -404,13 +502,12 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
- Update yarn.lock after dependabot update [`#2724`](https://github.com/Human-Connection/Human-Connection/pull/2724)
- build(deps): bump @nuxtjs/axios from 5.8.0 to 5.9.2 in /webapp [`#2657`](https://github.com/Human-Connection/Human-Connection/pull/2657)
- Update to version 0.2.1 [`#2722`](https://github.com/Human-Connection/Human-Connection/pull/2722)
- docs(deployment): Explain how to setup metrics (#2825) [`#2411`](https://github.com/Human-Connection/Human-Connection/issues/2411) [`#2777`](https://github.com/Human-Connection/Human-Connection/issues/2777)
- refactor(modules): Various import fixes [`#2773`](https://github.com/Human-Connection/Human-Connection/issues/2773) [`#2774`](https://github.com/Human-Connection/Human-Connection/issues/2774)
- feat(webapp): Display deployed version in footer [`#1831`](https://github.com/Human-Connection/Human-Connection/issues/1831)
- fix #2229 [`#2229`](https://github.com/Human-Connection/Human-Connection/issues/2229)
- Get rid of different factory files [`fc36729`](https://github.com/Human-Connection/Human-Connection/commit/fc367297e3e054f09b7f8f31788ab68d87f6babf)
- Refactor factory for comments [`2fc71d7`](https://github.com/Human-Connection/Human-Connection/commit/2fc71d75a5d5eab9c3467e94e00257ef6dd7d8a0)
- Refactor user factory [`2a79c53`](https://github.com/Human-Connection/Human-Connection/commit/2a79c53765b73f9b91691eb75f55cf8c9e48306e)
- build(deps-dev): bump @storybook/addon-actions in /webapp [`d0124bf`](https://github.com/Human-Connection/Human-Connection/commit/d0124bf2b4b4a641c9af76d6d2f7b5aa075ade90)
- refactor: Make `db:setup` init stage of `migrate` [`b063847`](https://github.com/Human-Connection/Human-Connection/commit/b063847849a84db885337dc8e84e75ddaf87011f)
- refactor and use base-button in SearchableInput [`fcbe612`](https://github.com/Human-Connection/Human-Connection/commit/fcbe6125f35c0dd23e2ba1ae63f539f5ef5990ea)
#### [v0.2.1](https://github.com/Human-Connection/Human-Connection/compare/v0.2.0...v0.2.1)

View File

@ -17,3 +17,9 @@ PRIVATE_KEY_PASSPHRASE="a7dsf78sadg87ad87sfagsadg78"
SENTRY_DSN_BACKEND=
COMMIT=
PUBLIC_REGISTRATION=false
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_ENDPOINT=
AWS_REGION=
AWS_BUCKET=

View File

@ -1,6 +1,6 @@
{
"name": "human-connection-backend",
"version": "0.4.2",
"version": "0.6.0",
"description": "GraphQL Backend for Human Connection",
"main": "src/index.js",
"scripts": {
@ -37,20 +37,21 @@
]
},
"dependencies": {
"@hapi/joi": "^17.1.0",
"@sentry/node": "^5.14.1",
"@hapi/joi": "^17.1.1",
"@sentry/node": "^5.15.4",
"apollo-cache-inmemory": "~1.6.5",
"apollo-client": "~2.6.8",
"apollo-link-context": "~1.0.19",
"apollo-link-http": "~1.5.16",
"apollo-server": "~2.11.0",
"apollo-server-express": "^2.11.0",
"aws-sdk": "^2.650.0",
"babel-plugin-transform-runtime": "^6.23.0",
"bcryptjs": "~2.4.3",
"cheerio": "~1.0.0-rc.3",
"cors": "~2.8.5",
"cross-env": "~7.0.2",
"date-fns": "2.10.0",
"date-fns": "2.11.1",
"debug": "~4.1.1",
"dotenv": "~8.2.0",
"express": "^4.17.1",
@ -61,9 +62,9 @@
"graphql-middleware": "~4.0.2",
"graphql-middleware-sentry": "^3.2.1",
"graphql-redis-subscriptions": "^2.2.1",
"graphql-shield": "~7.2.0",
"graphql-shield": "~7.2.2",
"graphql-tag": "~2.10.3",
"helmet": "~3.21.3",
"helmet": "~3.22.0",
"ioredis": "^4.16.0",
"jsonwebtoken": "~8.5.1",
"linkifyjs": "~2.1.8",
@ -80,56 +81,57 @@
"metascraper-lang-detector": "^4.10.2",
"metascraper-logo": "^5.11.6",
"metascraper-publisher": "^5.11.6",
"metascraper-soundcloud": "^5.11.6",
"metascraper-soundcloud": "^5.11.7",
"metascraper-title": "^5.11.6",
"metascraper-url": "^5.11.6",
"metascraper-video": "^5.11.6",
"metascraper-youtube": "^5.11.6",
"migrate": "^1.6.2",
"mime-types": "^2.1.26",
"minimatch": "^3.0.4",
"mustache": "^4.0.0",
"neo4j-driver": "^4.0.1",
"mustache": "^4.0.1",
"neo4j-driver": "^4.0.2",
"neo4j-graphql-js": "^2.11.5",
"neode": "^0.3.7",
"node-fetch": "~2.6.0",
"nodemailer": "^6.4.5",
"nodemailer": "^6.4.4",
"nodemailer-html-to-text": "^3.1.0",
"npm-run-all": "~4.1.5",
"request": "~2.88.2",
"sanitize-html": "~1.22.1",
"sanitize-html": "~1.22.0",
"slug": "~2.1.1",
"subscriptions-transport-ws": "^0.9.16",
"trunc-html": "~1.1.2",
"uuid": "~7.0.2",
"validator": "^12.2.0",
"uuid": "~7.0.3",
"validator": "^13.0.0",
"wait-on": "~4.0.1",
"xregexp": "^4.3.0"
},
"devDependencies": {
"@babel/cli": "~7.8.4",
"@babel/core": "~7.8.7",
"@babel/core": "~7.9.0",
"@babel/node": "~7.8.7",
"@babel/plugin-proposal-throw-expressions": "^7.8.3",
"@babel/preset-env": "~7.8.7",
"@babel/register": "^7.8.6",
"@babel/preset-env": "~7.9.0",
"@babel/register": "^7.9.0",
"apollo-server-testing": "~2.11.0",
"babel-core": "~7.0.0-0",
"babel-eslint": "~10.1.0",
"babel-jest": "~25.1.0",
"babel-jest": "~25.2.4",
"chai": "~4.2.0",
"cucumber": "~6.0.5",
"eslint": "~6.8.0",
"eslint-config-prettier": "~6.10.0",
"eslint-config-standard": "~14.1.0",
"eslint-plugin-import": "~2.20.1",
"eslint-config-prettier": "~6.10.1",
"eslint-config-standard": "~14.1.1",
"eslint-plugin-import": "~2.20.2",
"eslint-plugin-jest": "~23.8.2",
"eslint-plugin-node": "~11.0.0",
"eslint-plugin-node": "~11.1.0",
"eslint-plugin-prettier": "~3.1.2",
"eslint-plugin-promise": "~4.2.1",
"eslint-plugin-standard": "~4.0.1",
"jest": "~25.1.0",
"jest": "~25.2.4",
"nodemon": "~2.0.2",
"prettier": "~1.19.1",
"prettier": "~2.0.2",
"rosie": "^2.0.1",
"supertest": "~4.0.2"
},

View File

@ -7,7 +7,7 @@ import request from 'request'
import NitroDataSource from './NitroDataSource'
import router from './routes'
import Collections from './Collections'
import uuid from 'uuid/v4'
import { v4 as uuid } from 'uuid'
import CONFIG from '../config'
const debug = require('debug')('ea')
@ -202,14 +202,14 @@ export default class ActivityPub {
debug('is public addressed')
const sharedInboxEndpoints = await this.dataSource.getSharedInboxEndpoints()
// serve shared inbox endpoints
sharedInboxEndpoints.map(sharedInbox => {
sharedInboxEndpoints.map((sharedInbox) => {
return this.trySend(activity, fromName, new URL(sharedInbox).host, sharedInbox)
})
activity.to = activity.to.filter(recipient => {
activity.to = activity.to.filter((recipient) => {
return !isPublicAddressed({ to: recipient })
})
// serve the rest
activity.to.map(async recipient => {
activity.to.map(async (recipient) => {
debug('serve rest')
const actorObject = await this.getActorObject(recipient)
return this.trySend(activity, fromName, new URL(recipient).host, actorObject.inbox)
@ -219,7 +219,7 @@ export default class ActivityPub {
const actorObject = await this.getActorObject(activity.to)
return this.trySend(activity, fromName, new URL(activity.to).host, actorObject.inbox)
} else if (Array.isArray(activity.to)) {
activity.to.map(async recipient => {
activity.to.map(async (recipient) => {
const actorObject = await this.getActorObject(recipient)
return this.trySend(activity, fromName, new URL(recipient).host, actorObject.inbox)
})
@ -231,7 +231,7 @@ export default class ActivityPub {
return await signAndSend(activity, fromName, host, url)
} catch (e) {
if (tries > 0) {
setTimeout(function() {
setTimeout(function () {
return this.trySend(activity, fromName, host, url, --tries)
}, 20000)
}

View File

@ -99,7 +99,7 @@ export default class NitroDataSource {
followersCollection.totalItems = followersCount
debug(`followers = ${JSON.stringify(followers, null, 2)}`)
await Promise.all(
followers.map(async follower => {
followers.map(async (follower) => {
followersCollection.orderedItems.push(constructIdFromName(follower.slug))
}),
)
@ -161,7 +161,7 @@ export default class NitroDataSource {
followingCollection.totalItems = followingCount
await Promise.all(
following.map(async user => {
following.map(async (user) => {
followingCollection.orderedItems.push(await constructIdFromName(user.slug))
}),
)
@ -238,7 +238,7 @@ export default class NitroDataSource {
const outboxCollection = createOrderedCollectionPage(slug, 'outbox')
outboxCollection.totalItems = posts.length
await Promise.all(
posts.map(async post => {
posts.map(async (post) => {
outboxCollection.orderedItems.push(
await createArticleObject(
post.activityId,
@ -283,7 +283,7 @@ export default class NitroDataSource {
orderedItems = onlyNewestItem ? [orderedItems.pop()] : orderedItems
return Promise.all(
orderedItems.map(async follower => {
orderedItems.map(async (follower) => {
debug(`follower = ${follower}`)
const fromUserId = await this.ensureUser(follower)
debug(`fromUserId = ${fromUserId}`)
@ -311,7 +311,7 @@ export default class NitroDataSource {
const fromUserId = await this.ensureUser(constructIdFromName(fromUserName))
orderedItems = onlyNewestItem ? [orderedItems.pop()] : orderedItems
return Promise.all(
orderedItems.map(async following => {
orderedItems.map(async (following) => {
debug(`follower = ${following}`)
const toUserId = await this.ensureUser(following)
debug(`fromUserId = ${fromUserId}`)
@ -343,10 +343,7 @@ export default class NitroDataSource {
}
const title = postObject.summary
? postObject.summary
: postObject.content
.split(' ')
.slice(0, 5)
.join(' ')
: postObject.content.split(' ').slice(0, 5).join(' ')
const postId = extractIdFromActivityId(postObject.id)
debug('inside create post')
let result = await this.client.mutate({
@ -560,10 +557,7 @@ export default class NitroDataSource {
debug('ensureUser: user not exists.. createUser')
// user does not exist.. create it
const pw = crypto.randomBytes(16).toString('hex')
const slug = name
.toLowerCase()
.split(' ')
.join('-')
const slug = name.toLowerCase().split(' ').join('-')
const result = await this.client.mutate({
mutation: gql`
mutation {

View File

@ -7,7 +7,7 @@ const router = express.Router()
// Shared Inbox endpoint (federated Server)
// For now its only able to handle Note Activities!!
router.post('/', async function(req, res, next) {
router.post('/', async function (req, res, next) {
debug(`Content-Type = ${req.get('Content-Type')}`)
debug(`body = ${JSON.stringify(req.body, null, 2)}`)
debug(`Request headers = ${JSON.stringify(req.headers, null, 2)}`)

View File

@ -4,7 +4,7 @@ import express from 'express'
import cors from 'cors'
import verify from './verify'
export default function() {
export default function () {
const router = express.Router()
router.use(
'/activitypub/users',

View File

@ -21,7 +21,7 @@ export async function serveUser(req, res, next) {
}
`,
})
.catch(reason => {
.catch((reason) => {
debug(`serveUser User fetch error: ${reason}`)
})

View File

@ -7,7 +7,7 @@ import verify from './verify'
const router = express.Router()
const debug = require('debug')('ea:user')
router.get('/:name', async function(req, res, next) {
router.get('/:name', async function (req, res, next) {
debug('inside user.js -> serveUser')
await serveUser(req, res, next)
})
@ -45,7 +45,7 @@ router.get('/:name/outbox', (req, res) => {
}
})
router.post('/:name/inbox', verify, async function(req, res, next) {
router.post('/:name/inbox', verify, async function (req, res, next) {
debug(`body = ${JSON.stringify(req.body, null, 2)}`)
debug(`actorId = ${req.body.actor}`)
// const result = await saveActorId(req.body.actor)

View File

@ -5,7 +5,7 @@ import cors from 'cors'
const debug = require('debug')('ea:webfinger')
const regex = /acct:([a-z0-9_-]*)@([a-z0-9_-]*)/
const createWebFinger = name => {
const createWebFinger = (name) => {
const { host } = new URL(CONFIG.CLIENT_URI)
return {
subject: `acct:${name}@${host}`,
@ -30,11 +30,11 @@ export async function handler(req, res) {
const session = req.app.get('driver').session()
try {
const [slug] = await session.readTransaction(async t => {
const [slug] = await session.readTransaction(async (t) => {
const result = await t.run('MATCH (u:User {slug: $slug}) RETURN u.slug AS slug', {
slug: name,
})
return result.records.map(record => record.get('slug'))
return result.records.map((record) => record.get('slug'))
})
if (!slug)
return res.status(404).json({
@ -52,7 +52,7 @@ export async function handler(req, res) {
}
}
export default function() {
export default function () {
const router = express.Router()
router.use('/webfinger', cors(), express.urlencoded({ extended: true }), handler)
return router

View File

@ -13,7 +13,7 @@ const request = () => {
res = { status, contentType }
const req = {
app: {
get: key => {
get: (key) => {
return {
driver,
}[key]

View File

@ -69,7 +69,7 @@ export function verifySignature(url, headers) {
const usedHeaders = headersString.split(' ')
const verifyHeaders = {}
Object.keys(headers).forEach(key => {
Object.keys(headers).forEach((key) => {
if (usedHeaders.includes(key.toLowerCase())) {
verifyHeaders[key.toLowerCase()] = headers[key]
}
@ -119,7 +119,7 @@ function httpVerify(pubKey, signature, signingString, algorithm) {
// This function can be used to extract the signature,headers,algorithm etc. out of the Signature Header.
// Just pass what you want as key
function extractKeyValueFromSignatureHeader(signatureHeader, key) {
const keyString = signatureHeader.split(',').filter(el => {
const keyString = signatureHeader.split(',').filter((el) => {
return !!el.startsWith(key)
})[0]

View File

@ -60,13 +60,10 @@ export function sendCollection(collectionName, req, res) {
function attachThenCatch(promise, res) {
return promise
.then(collection => {
res
.status(200)
.contentType('application/activity+json')
.send(collection)
.then((collection) => {
res.status(200).contentType('application/activity+json').send(collection)
})
.catch(err => {
.catch((err) => {
debug(`error getting a Collection: = ${err}`)
res.status(500).end()
})

View File

@ -53,7 +53,7 @@ export function signAndSend(activity, fromName, targetDomain, url) {
}
`,
})
.then(result => {
.then((result) => {
if (result.error) {
reject(result.error)
} else {

View File

@ -18,6 +18,11 @@ const {
SMTP_PASSWORD,
SENTRY_DSN_BACKEND,
COMMIT,
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
AWS_ENDPOINT,
AWS_REGION,
AWS_BUCKET,
NEO4J_URI = 'bolt://localhost:7687',
NEO4J_USERNAME = 'neo4j',
NEO4J_PASSWORD = 'neo4j',
@ -36,7 +41,7 @@ export const requiredConfigs = {
if (require.resolve) {
// are we in a nodejs environment?
Object.entries(requiredConfigs).map(entry => {
Object.entries(requiredConfigs).map((entry) => {
if (!entry[1]) {
throw new Error(`ERROR: "${entry[0]}" env variable is missing.`)
}
@ -64,7 +69,20 @@ export const developmentConfigs = {
}
export const sentryConfigs = { SENTRY_DSN_BACKEND, COMMIT }
export const redisConfiig = { REDIS_DOMAIN, REDIS_PORT, REDIS_PASSWORD }
export const redisConfigs = { REDIS_DOMAIN, REDIS_PORT, REDIS_PASSWORD }
const S3_CONFIGURED =
AWS_ACCESS_KEY_ID && AWS_SECRET_ACCESS_KEY && AWS_ENDPOINT && AWS_REGION && AWS_BUCKET
export const s3Configs = {
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
AWS_ENDPOINT,
AWS_REGION,
AWS_BUCKET,
S3_CONFIGURED,
}
export default {
...requiredConfigs,
...smtpConfigs,
@ -72,5 +90,6 @@ export default {
...serverConfigs,
...developmentConfigs,
...sentryConfigs,
...redisConfiig,
...redisConfigs,
...s3Configs,
}

View File

@ -4,7 +4,7 @@ if (process.env.NODE_ENV === 'production') {
throw new Error(`You cannot clean the database in production environment!`)
}
;(async function() {
;(async function () {
try {
await cleanDatabase()
console.log('Successfully deleted all nodes and relations!') // eslint-disable-line no-console

View File

@ -4,14 +4,21 @@ import slugify from 'slug'
import { hashSync } from 'bcryptjs'
import { Factory } from 'rosie'
import { getDriver, getNeode } from './neo4j'
import CONFIG from '../config/index.js'
const neode = getNeode()
const uniqueImageUrl = (imageUrl) => {
const newUrl = new URL(imageUrl, CONFIG.CLIENT_URI)
newUrl.search = `random=${uuid()}`
return newUrl.toString()
}
export const cleanDatabase = async (options = {}) => {
const { driver = getDriver() } = options
const session = driver.session()
try {
await session.writeTransaction(transaction => {
await session.writeTransaction((transaction) => {
return transaction.run(
`
MATCH (everything)
@ -39,14 +46,23 @@ Factory.define('badge')
return neode.create('Badge', buildObject)
})
Factory.define('userWithoutEmailAddress')
Factory.define('image')
.attr('url', faker.image.unsplash.imageUrl)
.attr('aspectRatio', 1)
.attr('alt', faker.lorem.sentence)
.after((buildObject, options) => {
const { url: imageUrl } = buildObject
if (imageUrl) buildObject.url = uniqueImageUrl(imageUrl)
return neode.create('Image', buildObject)
})
Factory.define('basicUser')
.option('password', '1234')
.attrs({
id: uuid,
name: faker.name.findName,
password: '1234',
role: 'user',
avatar: faker.internet.avatar,
about: faker.lorem.paragraph,
termsAndConditionsAgreedVersion: '0.0.1',
termsAndConditionsAgreedAt: '2019-08-01T10:47:19.212Z',
@ -57,53 +73,63 @@ Factory.define('userWithoutEmailAddress')
.attr('slug', ['slug', 'name'], (slug, name) => {
return slug || slugify(name, { lower: true })
})
.attr('encryptedPassword', ['password'], password => {
.attr('encryptedPassword', ['password'], (password) => {
return hashSync(password, 10)
})
Factory.define('userWithoutEmailAddress')
.extend('basicUser')
.after(async (buildObject, options) => {
return neode.create('User', buildObject)
})
Factory.define('user')
.extend('userWithoutEmailAddress')
.extend('basicUser')
.option('email', faker.internet.exampleEmail)
.option('avatar', () =>
Factory.build('image', {
url: faker.internet.avatar(),
}),
)
.after(async (buildObject, options) => {
const [user, email] = await Promise.all([
buildObject,
const [user, email, avatar] = await Promise.all([
neode.create('User', buildObject),
neode.create('EmailAddress', { email: options.email }),
options.avatar,
])
await Promise.all([user.relateTo(email, 'primaryEmail'), email.relateTo(user, 'belongsTo')])
if (avatar) await user.relateTo(avatar, 'avatar')
return user
})
Factory.define('post')
.option('categoryIds', [])
.option('categories', ['categoryIds'], categoryIds => {
if (categoryIds.length) return Promise.all(categoryIds.map(id => neode.find('Category', id)))
.option('categories', ['categoryIds'], (categoryIds) => {
if (categoryIds.length) return Promise.all(categoryIds.map((id) => neode.find('Category', id)))
// there must be at least one category
return Promise.all([Factory.build('category')])
})
.option('tagIds', [])
.option('tags', ['tagIds'], tagIds => {
return Promise.all(tagIds.map(id => neode.find('Tag', id)))
.option('tags', ['tagIds'], (tagIds) => {
return Promise.all(tagIds.map((id) => neode.find('Tag', id)))
})
.option('authorId', null)
.option('author', ['authorId'], authorId => {
.option('author', ['authorId'], (authorId) => {
if (authorId) return neode.find('User', authorId)
return Factory.build('user')
})
.option('pinnedBy', null)
.option('image', () => Factory.build('image'))
.attrs({
id: uuid,
title: faker.lorem.sentence,
content: faker.lorem.paragraphs,
image: faker.image.unsplash.imageUrl,
visibility: 'public',
deleted: false,
imageBlurred: false,
imageAspectRatio: 1.333,
})
.attr('pinned', ['pinned'], pinned => {
.attr('pinned', ['pinned'], (pinned) => {
// Convert false to null
return pinned || null
})
@ -113,21 +139,23 @@ Factory.define('post')
.attr('slug', ['slug', 'title'], (slug, title) => {
return slug || slugify(title, { lower: true })
})
.attr('language', ['language'], language => {
.attr('language', ['language'], (language) => {
return language || 'en'
})
.after(async (buildObject, options) => {
const [post, author, categories, tags] = await Promise.all([
const [post, author, image, categories, tags] = await Promise.all([
neode.create('Post', buildObject),
options.author,
options.image,
options.categories,
options.tags,
])
await Promise.all([
post.relateTo(author, 'author'),
Promise.all(categories.map(c => c.relateTo(post, 'post'))),
Promise.all(tags.map(t => t.relateTo(post, 'post'))),
Promise.all(categories.map((c) => c.relateTo(post, 'post'))),
Promise.all(tags.map((t) => t.relateTo(post, 'post'))),
])
if (image) await post.relateTo(image, 'image')
if (buildObject.pinned) {
const pinnedBy = await (options.pinnedBy || Factory.build('user', { role: 'admin' }))
await pinnedBy.relateTo(post, 'pinned')
@ -137,12 +165,12 @@ Factory.define('post')
Factory.define('comment')
.option('postId', null)
.option('post', ['postId'], postId => {
.option('post', ['postId'], (postId) => {
if (postId) return neode.find('Post', postId)
return Factory.build('post')
})
.option('authorId', null)
.option('author', ['authorId'], authorId => {
.option('author', ['authorId'], (authorId) => {
if (authorId) return neode.find('User', authorId)
return Factory.build('user')
})

View File

@ -6,13 +6,14 @@ class Store {
const { driver } = neode
const session = driver.session()
// eslint-disable-next-line no-console
const writeTxResultPromise = session.writeTransaction(async txc => {
const writeTxResultPromise = session.writeTransaction(async (txc) => {
await txc.run('CALL apoc.schema.assert({},{},true)') // drop all indices
return Promise.all(
[
'CALL db.index.fulltext.createNodeIndex("post_fulltext_search",["Post"],["title", "content"])',
'CALL db.index.fulltext.createNodeIndex("user_fulltext_search",["User"],["name", "slug"])',
].map(statement => txc.run(statement)),
'CALL db.index.fulltext.createNodeIndex("tag_fulltext_search",["Tag"],["id"])',
].map((statement) => txc.run(statement)),
)
})
try {
@ -33,11 +34,11 @@ class Store {
async load(next) {
const driver = getDriver()
const session = driver.session()
const readTxResultPromise = session.readTransaction(async txc => {
const readTxResultPromise = session.readTransaction(async (txc) => {
const result = await txc.run(
'MATCH (migration:Migration) RETURN migration {.*} ORDER BY migration.timestamp DESC',
)
return result.records.map(r => r.get('migration'))
return result.records.map((r) => r.get('migration'))
})
try {
const migrations = await readTxResultPromise
@ -62,9 +63,9 @@ class Store {
const driver = getDriver()
const session = driver.session()
const { migrations } = set
const writeTxResultPromise = session.writeTransaction(txc => {
const writeTxResultPromise = session.writeTransaction((txc) => {
return Promise.all(
migrations.map(async migration => {
migrations.map(async (migration) => {
const { title, description, timestamp } = migration
const properties = { title, description, timestamp }
const migrationResult = await txc.run(

View File

@ -40,6 +40,7 @@ export async function down(next) {
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}

View File

@ -18,13 +18,13 @@ export function up(next) {
rxSession
.beginTransaction()
.pipe(
flatMap(txc =>
flatMap((txc) =>
concat(
txc
.run('MATCH (email:EmailAddress) RETURN email {.email}')
.records()
.pipe(
map(record => {
map((record) => {
const { email } = record.get('email')
const normalizedEmail = normalizeEmail(email)
return { email, normalizedEmail }
@ -45,7 +45,7 @@ export function up(next) {
)
.records()
.pipe(
map(r => ({
map((r) => ({
oldEmail: email,
email: r.get('email'),
user: r.get('user'),
@ -54,7 +54,7 @@ export function up(next) {
}),
),
txc.commit(),
).pipe(catchError(err => txc.rollback().pipe(throwError(err)))),
).pipe(catchError((err) => txc.rollback().pipe(throwError(err)))),
),
)
.subscribe({
@ -72,7 +72,7 @@ export function up(next) {
console.log('Merging of duplicate users completed')
next()
},
error: error => {
error: (error) => {
next(new Error(error), null)
},
})

View File

@ -12,7 +12,7 @@ export function up(next) {
rxSession
.beginTransaction()
.pipe(
flatMap(transaction =>
flatMap((transaction) =>
concat(
transaction
.run(
@ -23,7 +23,7 @@ export function up(next) {
)
.records()
.pipe(
map(record => {
map((record) => {
const { id: locationId } = record.get('location')
return { locationId }
}),
@ -40,7 +40,7 @@ export function up(next) {
)
.records()
.pipe(
map(record => ({
map((record) => ({
location: record.get('location'),
updatedLocation: record.get('updatedLocation'),
})),
@ -48,7 +48,7 @@ export function up(next) {
}),
),
transaction.commit(),
).pipe(catchError(error => transaction.rollback().pipe(throwError(error)))),
).pipe(catchError((error) => transaction.rollback().pipe(throwError(error)))),
),
)
.subscribe({
@ -66,7 +66,7 @@ export function up(next) {
console.log('Merging of duplicate locations completed')
next()
},
error: error => {
error: (error) => {
next(new Error(error), null)
},
})

View File

@ -8,7 +8,7 @@ values lat=10.0 and lng=53.55, which is close to the horn of Africa,
but it is lat=53.55 and lng=10.0
`
const swap = async function(next) {
const swap = async function (next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()

View File

@ -0,0 +1,57 @@
import { getDriver } from '../../db/neo4j'
export const description =
'This migration adds a fulltext index for the tags in order to search for Hasthags.'
export async function up(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
await transaction.run(`
CALL db.index.fulltext.createNodeIndex("tag_fulltext_search",["Tag"],["id"])
`)
await transaction.commit()
next()
} catch (error) {
const { message } = error
if (message.includes('There already exists an index')) {
// all fine
// eslint-disable-next-line no-console
console.log(message)
next()
} else {
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
}
} finally {
session.close()
}
}
export async function down(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
// Implement your migration here.
await transaction.run(`
CALL db.index.fulltext.drop("tag_fulltext_search")
`)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}
}

View File

@ -0,0 +1,60 @@
import { getDriver } from '../../db/neo4j'
export const description = `
We introduced a new node label 'Image' and we need a primary key for it. Best
would probably be the 'url' property which should be unique and would also
prevent us from overwriting existing images.
`
export async function up(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
// Implement your migration here.
await transaction.run(`
CREATE CONSTRAINT ON ( image:Image ) ASSERT image.url IS UNIQUE
`)
await transaction.commit()
next()
} catch (error) {
const { message } = error
if (message.includes('There already exists an index')) {
// all fine
// eslint-disable-next-line no-console
console.log(message)
next()
} else {
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
}
} finally {
session.close()
}
}
export async function down(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
// Implement your migration here.
await transaction.run(`
DROP CONSTRAINT ON ( image:Image ) ASSERT image.url IS UNIQUE
`)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
} finally {
session.close()
}
}

View File

@ -0,0 +1,107 @@
import { getDriver } from '../../db/neo4j'
import { existsSync, createReadStream } from 'fs'
import path from 'path'
import { S3 } from 'aws-sdk'
import mime from 'mime-types'
import { s3Configs } from '../../config'
import https from 'https'
export const description = `
Upload all image files to a S3 compatible object storage in order to reduce
load on our backend.
`
export async function up(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
const agent = new https.Agent({
maxSockets: 5,
})
const {
AWS_ENDPOINT: endpoint,
AWS_REGION: region,
AWS_BUCKET: Bucket,
S3_CONFIGURED,
} = s3Configs
if (!S3_CONFIGURED) {
// eslint-disable-next-line no-console
console.log('No S3 given, cannot upload image files')
return
}
const s3 = new S3({ region, endpoint, httpOptions: { agent } })
try {
// Implement your migration here.
const { records } = await transaction.run('MATCH (image:Image) RETURN image.url as url')
let urls = records.map((r) => r.get('url'))
urls = urls.filter((url) => url.startsWith('/uploads'))
const locations = await Promise.all(
urls
.map((url) => {
return async () => {
const { pathname } = new URL(url, 'http://example.org')
const fileLocation = path.join(__dirname, `../../../public/${pathname}`)
const s3Location = `original${pathname}`
if (existsSync(fileLocation)) {
const mimeType = mime.lookup(fileLocation)
const params = {
Bucket,
Key: s3Location,
ACL: 'public-read',
ContentType: mimeType || 'image/jpeg',
Body: createReadStream(fileLocation),
}
const data = await s3.upload(params).promise()
const { Location: spacesUrl } = data
const updatedRecord = await transaction.run(
'MATCH (image:Image {url: $url}) SET image.url = $spacesUrl RETURN image.url as url',
{ url, spacesUrl },
)
const [updatedUrl] = updatedRecord.records.map((record) => record.get('url'))
return updatedUrl
}
}
})
.map((p) => p()),
)
// eslint-disable-next-line no-console
console.log('this is locations', locations)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}
}
export async function down(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
// Implement your migration here.
await transaction.run(``)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
} finally {
session.close()
}
}

View File

@ -0,0 +1,101 @@
/* eslint-disable no-console */
import { getDriver } from '../../db/neo4j'
export const description = `
Refactor all our image properties on posts and users to a dedicated type
"Image" which contains metadata and image file urls.
`
const printSummaries = (summaries) => {
console.log('=========================================')
summaries.forEach((stat) => {
console.log(stat.query.text)
console.log(JSON.stringify(stat.counters, null, 2))
})
console.log('=========================================')
}
export async function up() {
const driver = getDriver()
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async (txc) => {
const runs = await Promise.all(
[
`
MATCH (post:Post)
WHERE post.image IS NOT NULL AND post.deleted = FALSE
MERGE(image:Image {url: post.image})
CREATE (post)-[:HERO_IMAGE]->(image)
SET
image.sensitive = post.imageBlurred,
image.aspectRatio = post.imageAspectRatio
REMOVE
post.image,
post.imageBlurred,
post.imageAspectRatio
`,
`
MATCH (user:User)
WHERE user.avatar IS NOT NULL AND user.deleted = FALSE
MERGE(avatar:Image {url: user.avatar})
CREATE (user)-[:AVATAR_IMAGE]->(avatar)
REMOVE user.avatar
`,
`
MATCH (user:User)
WHERE user.coverImg IS NOT NULL AND user.deleted = FALSE
MERGE(coverImage:Image {url: user.coverImg})
CREATE (user)-[:COVER_IMAGE]->(coverImage)
REMOVE user.coverImg
`,
].map((s) => txc.run(s)),
)
return runs.map(({ summary }) => summary)
})
try {
const stats = await writeTxResultPromise
console.log('Created image nodes from all user avatars and post images.')
printSummaries(stats)
} finally {
session.close()
}
}
export async function down() {
const driver = getDriver()
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async (txc) => {
const runs = await Promise.all(
[
`
MATCH (post)-[:HERO_IMAGE]->(image:Image)
SET
post.image = image.url,
post.imageBlurred = image.sensitive,
post.imageAspectRatio = image.aspectRatio
DETACH DELETE image
`,
`
MATCH(user)-[:AVATAR_IMAGE]->(avatar:Image)
SET user.avatar = avatar.url
DETACH DELETE avatar
`,
`
MATCH(user)-[:COVER_IMAGE]->(coverImage:Image)
SET user.coverImg = coverImage.url
DETACH DELETE coverImage
`,
].map((s) => txc.run(s)),
)
return runs.map(({ summary }) => summary)
})
try {
const stats = await writeTxResultPromise
console.log('UNDO: Split images from users and posts.')
printSummaries(stats)
} finally {
session.close()
}
}

View File

@ -0,0 +1,44 @@
import { getDriver } from '../../db/neo4j'
export const description =
'We should not maintain obsolete attributes for users who have been deleted.'
export async function up(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
const updateDeletedUserAttributes = await transaction.run(`
MATCH (user:User)
WHERE user.deleted = TRUE
SET user.createdAt = 'UNAVAILABLE'
SET user.updatedAt = 'UNAVAILABLE'
SET user.lastActiveAt = 'UNAVAILABLE'
SET user.termsAndConditionsAgreedVersion = 'UNAVAILABLE'
SET user.avatar = null
SET user.coverImg = null
RETURN user {.*};
`)
try {
// Implement your migration here.
const users = await updateDeletedUserAttributes.records.map((record) => record.get('user'))
// eslint-disable-next-line no-console
console.log(users)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}
}
export async function down(next) {
// eslint-disable-next-line no-console
console.log('Irreversible migration')
next()
}

View File

@ -0,0 +1,46 @@
import { getDriver } from '../../db/neo4j'
export const description =
'We should not maintain obsolete attributes for posts which have been deleted.'
export async function up(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
const updateDeletedPostsAttributes = await transaction.run(`
MATCH (post:Post)
WHERE post.deleted = TRUE
SET post.language = 'UNAVAILABLE'
SET post.createdAt = 'UNAVAILABLE'
SET post.updatedAt = 'UNAVAILABLE'
SET post.content = 'UNAVAILABLE'
SET post.title = 'UNAVAILABLE'
SET post.visibility = 'UNAVAILABLE'
SET post.contentExcerpt = 'UNAVAILABLE'
SET post.image = null
RETURN post {.*};
`)
try {
// Implement your migration here.
const posts = await updateDeletedPostsAttributes.records.map((record) => record.get('post'))
// eslint-disable-next-line no-console
console.log(posts)
await transaction.commit()
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}
}
export async function down(next) {
// eslint-disable-next-line no-console
console.log('Irreversible migration')
next()
}

View File

@ -0,0 +1,61 @@
import { getDriver } from '../../db/neo4j'
import { existsSync } from 'fs'
export const description = `
In this review:
https://github.com/Human-Connection/Human-Connection/pull/3262#discussion_r398634249
I brought up that we may have image nodes with danling urls (urls that don't
point to local file on disk). I would prefer to remove those urls to avoid
unnecessary 404 errors.
`
export async function up(next) {
const driver = getDriver()
const session = driver.session()
const transaction = session.beginTransaction()
try {
// Implement your migration here.
const { records } = await transaction.run(`
MATCH(image:Image)
WHERE image.url STARTS WITH '/'
RETURN image.url as url
`)
const urls = records.map((record) => record.get('url'))
const danglingUrls = urls.filter((url) => {
const fileLocation = `public${url}`
return !existsSync(fileLocation)
})
await transaction.run(
`
MATCH(image:Image)
WHERE image.url IN $danglingUrls
DETACH DELETE image
`,
{ danglingUrls },
)
await transaction.commit()
if (danglingUrls.length) {
// eslint-disable-next-line no-console
console.log(`
Removed ${danglingUrls.length} dangling urls.\n
===============================================
${danglingUrls.join('\n')}
`)
}
next()
} catch (error) {
// eslint-disable-next-line no-console
console.log(error)
await transaction.rollback()
// eslint-disable-next-line no-console
console.log('rolled back')
throw new Error(error)
} finally {
session.close()
}
}
export async function down() {
throw new Error('Irreversible migration')
}

View File

@ -9,7 +9,7 @@ import { gql } from '../helpers/jest'
const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
/* eslint-disable no-multi-spaces */
;(async function() {
;(async function () {
let authenticatedUser = null
const driver = getDriver()
const neode = getNeode()
@ -389,13 +389,15 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
{
id: 'p0',
language: sample(languages),
image: faker.image.unsplash.food(300, 169),
imageBlurred: true,
imageAspectRatio: 300 / 169,
},
{
categoryIds: ['cat16'],
author: peterLustig,
image: Factory.build('image', {
url: faker.image.unsplash.food(300, 169),
sensitive: true,
aspectRatio: 300 / 169,
}),
},
),
Factory.build(
@ -403,12 +405,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
{
id: 'p1',
language: sample(languages),
image: faker.image.unsplash.technology(300, 1500),
imageAspectRatio: 300 / 1500,
},
{
categoryIds: ['cat1'],
author: bobDerBaumeister,
image: Factory.build('image', {
url: faker.image.unsplash.technology(300, 1500),
aspectRatio: 300 / 1500,
}),
},
),
Factory.build(
@ -449,12 +453,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
{
id: 'p6',
language: sample(languages),
image: faker.image.unsplash.buildings(300, 857),
imageAspectRatio: 300 / 857,
},
{
categoryIds: ['cat6'],
author: peterLustig,
image: Factory.build('image', {
url: faker.image.unsplash.buildings(300, 857),
aspectRatio: 300 / 857,
}),
},
),
Factory.build(
@ -472,11 +478,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
'post',
{
id: 'p10',
imageBlurred: true,
},
{
categoryIds: ['cat10'],
author: dewey,
image: Factory.build('image', {
sensitive: true,
}),
},
),
Factory.build(
@ -484,12 +492,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
{
id: 'p11',
language: sample(languages),
image: faker.image.unsplash.people(300, 901),
imageAspectRatio: 300 / 901,
},
{
categoryIds: ['cat11'],
author: louie,
image: Factory.build('image', {
url: faker.image.unsplash.people(300, 901),
aspectRatio: 300 / 901,
}),
},
),
Factory.build(
@ -508,12 +518,14 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
{
id: 'p14',
language: sample(languages),
image: faker.image.unsplash.objects(300, 200),
imageAspectRatio: 300 / 450,
},
{
categoryIds: ['cat14'],
author: jennyRostock,
image: Factory.build('image', {
url: faker.image.unsplash.objects(300, 200),
aspectRatio: 300 / 450,
}),
},
),
Factory.build(
@ -539,22 +551,8 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
const hashtagAndMention1 =
'The new physics of <a class="hashtag" data-hashtag-id="QuantenFlussTheorie" href="/?hashtag=QuantenFlussTheorie">#QuantenFlussTheorie</a> can explain <a class="hashtag" data-hashtag-id="QuantumGravity" href="/?hashtag=QuantumGravity">#QuantumGravity</a>! <a class="mention" data-mention-id="u1" href="/profile/u1">@peter-lustig</a> got that already. ;-)'
const createPostMutation = gql`
mutation(
$id: ID
$title: String!
$content: String!
$categoryIds: [ID]
$imageBlurred: Boolean
$imageAspectRatio: Float
) {
CreatePost(
id: $id
title: $title
content: $content
categoryIds: $categoryIds
imageBlurred: $imageBlurred
imageAspectRatio: $imageAspectRatio
) {
mutation($id: ID, $title: String!, $content: String!, $categoryIds: [ID]) {
CreatePost(id: $id, title: $title, content: $content, categoryIds: $categoryIds) {
id
}
}
@ -568,7 +566,6 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
title: `Nature Philosophy Yoga`,
content: hashtag1,
categoryIds: ['cat2'],
imageAspectRatio: 300 / 200,
},
}),
mutate({
@ -578,7 +575,6 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
title: 'This is post #7',
content: `${mention1} ${faker.lorem.paragraph()}`,
categoryIds: ['cat7'],
imageAspectRatio: 300 / 180,
},
}),
mutate({
@ -589,7 +585,6 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
title: `Quantum Flow Theory explains Quantum Gravity`,
content: hashtagAndMention1,
categoryIds: ['cat8'],
imageAspectRatio: 300 / 900,
},
}),
mutate({
@ -599,12 +594,11 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
title: 'This is post #12',
content: `${mention2} ${faker.lorem.paragraph()}`,
categoryIds: ['cat12'],
imageAspectRatio: 300 / 200,
},
}),
])
const [p2, p7, p8, p12] = await Promise.all(
['p2', 'p7', 'p8', 'p12'].map(id => neode.find('Post', id)),
['p2', 'p7', 'p8', 'p12'].map((id) => neode.find('Post', id)),
)
authenticatedUser = null
@ -1020,12 +1014,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
[...Array(30).keys()].map(() =>
Factory.build(
'post',
{
image: faker.image.unsplash.objects(),
},
{},
{
categoryIds: ['cat1'],
author: jennyRostock,
image: Factory.build('image', {
url: faker.image.unsplash.objects(),
}),
},
),
),
@ -1074,12 +1069,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
[...Array(21).keys()].map(() =>
Factory.build(
'post',
{
image: faker.image.unsplash.buildings(),
},
{},
{
categoryIds: ['cat1'],
author: peterLustig,
image: Factory.build('image', {
url: faker.image.unsplash.buildings(),
}),
},
),
),
@ -1128,12 +1124,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
[...Array(11).keys()].map(() =>
Factory.build(
'post',
{
image: faker.image.unsplash.food(),
},
{},
{
categoryIds: ['cat1'],
author: dewey,
image: Factory.build('image', {
url: faker.image.unsplash.food(),
}),
},
),
),
@ -1182,12 +1179,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
[...Array(16).keys()].map(() =>
Factory.build(
'post',
{
image: faker.image.unsplash.technology(),
},
{},
{
categoryIds: ['cat1'],
author: louie,
image: Factory.build('image', {
url: faker.image.unsplash.technology(),
}),
},
),
),
@ -1236,12 +1234,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
[...Array(45).keys()].map(() =>
Factory.build(
'post',
{
image: faker.image.unsplash.people(),
},
{},
{
categoryIds: ['cat1'],
author: bobDerBaumeister,
image: Factory.build('image', {
url: faker.image.unsplash.people(),
}),
},
),
),
@ -1290,12 +1289,13 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
[...Array(8).keys()].map(() =>
Factory.build(
'post',
{
image: faker.image.unsplash.nature(),
},
{},
{
categoryIds: ['cat1'],
author: huey,
image: Factory.build('image', {
url: faker.image.unsplash.nature(),
}),
},
),
),

View File

@ -1,6 +1,6 @@
import { hashSync } from 'bcryptjs'
export default function(args) {
export default function (args) {
args.encryptedPassword = hashSync(args.password, 10)
delete args.password
return args

View File

@ -18,7 +18,7 @@ function walkRecursive(data, fields, callback, _key) {
})
} else if (data && typeof data === 'object') {
// lets get some keys and stir them
Object.keys(data).forEach(k => {
Object.keys(data).forEach((k) => {
data[k] = walkRecursive(data[k], fields, callback, k)
})
}

View File

@ -13,17 +13,17 @@ export default async (driver, authorizationHeader) => {
}
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const updateUserLastActiveTransactionResponse = await transaction.run(
`
`
MATCH (user:User {id: $id, deleted: false, disabled: false })
SET user.lastActiveAt = toString(datetime())
RETURN user {.id, .slug, .name, .avatar, .email, .role, .disabled, .actorId}
RETURN user {.id, .slug, .name, .role, .disabled, .actorId}
LIMIT 1
`,
{ id },
)
return updateUserLastActiveTransactionResponse.records.map(record => record.get('user'))
return updateUserLastActiveTransactionResponse.records.map((record) => record.get('user'))
})
try {
const [currentUser] = await writeTxResultPromise

View File

@ -69,23 +69,23 @@ describe('decode', () => {
{
role: 'user',
name: 'Jenny Rostock',
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg',
id: 'u3',
slug: 'jenny-rostock',
},
{
image: Factory.build('image', {
url: 'https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg',
}),
email: 'user@example.org',
},
)
})
it('returns user object except email', async () => {
it('returns user object without email', async () => {
await expect(decode(driver, authorizationHeader)).resolves.toMatchObject({
role: 'user',
name: 'Jenny Rostock',
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg',
id: 'u3',
email: null,
slug: 'jenny-rostock',
})
})

View File

@ -18,7 +18,7 @@ if (!hasEmailConfig) {
console.log('Warning: Email middleware will not try to send mails.')
}
} else {
sendMail = async templateArgs => {
sendMail = async (templateArgs) => {
const transporter = nodemailer.createTransport({
host: CONFIG.SMTP_HOST,
port: CONFIG.SMTP_PORT,

View File

@ -1,7 +1,7 @@
import fs from 'fs'
import path from 'path'
const readFile = fileName => fs.readFileSync(path.join(__dirname, fileName), 'utf-8')
const readFile = (fileName) => fs.readFileSync(path.join(__dirname, fileName), 'utf-8')
export const signup = readFile('./signup.html')
export const passwordReset = readFile('./resetPassword.html')

View File

@ -8,7 +8,7 @@ import { exec, build } from 'xregexp/xregexp-all.js'
// 2. If it starts with a digit '0-9' than a unicode letter has to follow.
const regX = build('^((\\pL+[\\pL0-9]*)|([0-9]+\\pL+[\\pL0-9]*))$')
export default function(content) {
export default function (content) {
if (!content) return []
const $ = cheerio.load(content)
// We can not search for class '.hashtag', because the classes are removed at the 'xss' middleware.
@ -19,7 +19,7 @@ export default function(content) {
})
.get()
const hashtags = []
ids.forEach(id => {
ids.forEach((id) => {
const match = exec(id, regX)
if (match != null) {
hashtags.push(match[1])

View File

@ -5,7 +5,7 @@ const updateHashtagsOfPost = async (postId, hashtags, context) => {
const session = context.driver.session()
try {
await session.writeTransaction(txc => {
await session.writeTransaction((txc) => {
return txc.run(
`
MATCH (post:Post { id: $postId})

View File

@ -2,21 +2,21 @@ import cloneDeep from 'lodash/cloneDeep'
const _includeFieldsRecursively = (selectionSet, includedFields) => {
if (!selectionSet) return
includedFields.forEach(includedField => {
includedFields.forEach((includedField) => {
selectionSet.selections.unshift({
kind: 'Field',
name: { kind: 'Name', value: includedField },
})
})
selectionSet.selections.forEach(selection => {
selectionSet.selections.forEach((selection) => {
_includeFieldsRecursively(selection.selectionSet, includedFields)
})
}
const includeFieldsRecursively = includedFields => {
const includeFieldsRecursively = (includedFields) => {
return (resolve, root, args, context, resolveInfo) => {
const copy = cloneDeep(resolveInfo)
copy.fieldNodes.forEach(fieldNode => {
copy.fieldNodes.forEach((fieldNode) => {
_includeFieldsRecursively(fieldNode.selectionSet, includedFields)
})
return resolve(root, args, context, copy)

View File

@ -15,7 +15,7 @@ import hashtags from './hashtags/hashtagsMiddleware'
import email from './email/emailMiddleware'
import sentry from './sentryMiddleware'
export default schema => {
export default (schema) => {
const middlewares = {
sentry,
permissions,
@ -51,7 +51,7 @@ export default schema => {
// add permisions middleware at the first position (unless we're seeding)
if (CONFIG.DISABLED_MIDDLEWARES) {
const disabledMiddlewares = CONFIG.DISABLED_MIDDLEWARES.split(',')
order = order.filter(key => {
order = order.filter((key) => {
if (disabledMiddlewares.includes(key)) {
/* eslint-disable-next-line no-console */
console.log(`Warning: Disabled "${disabledMiddlewares}" middleware.`)
@ -60,6 +60,6 @@ export default schema => {
})
}
const appliedMiddlewares = order.map(key => middlewares[key])
const appliedMiddlewares = order.map((key) => middlewares[key])
return applyMiddleware(schema, ...appliedMiddlewares)
}

View File

@ -1,6 +1,6 @@
import cheerio from 'cheerio'
export default content => {
export default (content) => {
if (!content) return []
const $ = cheerio.load(content)
const userIds = $('a.mention[data-mention-id]')
@ -9,7 +9,7 @@ export default content => {
})
.get()
return userIds
.map(id => id.trim())
.filter(id => !!id)
.map((id) => id.trim())
.filter((id) => !!id)
.filter((id, index, allIds) => allIds.indexOf(id) === index)
}

View File

@ -7,7 +7,7 @@ const publishNotifications = async (...promises) => {
const notifications = await Promise.all(promises)
notifications
.flat()
.forEach(notificationAdded => pubsub.publish(NOTIFICATION_ADDED, { notificationAdded }))
.forEach((notificationAdded) => pubsub.publish(NOTIFICATION_ADDED, { notificationAdded }))
}
const debug = require('debug')('human-connection-backend:notificationsMiddleware')
@ -28,7 +28,7 @@ const handleContentDataOfComment = async (resolve, root, args, context, resolveI
let idsOfUsers = extractMentionedUsers(content)
const comment = await resolve(root, args, context, resolveInfo)
const [postAuthor] = await postAuthorOfComment(comment.id, { context })
idsOfUsers = idsOfUsers.filter(id => id !== postAuthor.id)
idsOfUsers = idsOfUsers.filter((id) => id !== postAuthor.id)
await publishNotifications(
notifyUsersOfMention('Comment', comment.id, idsOfUsers, 'mentioned_in_comment', context),
notifyUsersOfComment('Comment', comment.id, postAuthor.id, 'commented_on_post', context),
@ -40,7 +40,7 @@ const postAuthorOfComment = async (commentId, { context }) => {
const session = context.driver.session()
let postAuthorId
try {
postAuthorId = await session.readTransaction(transaction => {
postAuthorId = await session.readTransaction((transaction) => {
return transaction.run(
`
MATCH (author:User)-[:WROTE]->(:Post)<-[:COMMENTS]-(:Comment { id: $commentId })

View File

@ -47,7 +47,7 @@ const isAuthor = rule({
if (!user) return false
const { id: resourceId } = args
const session = driver.session()
const authorReadTxPromise = session.readTransaction(async transaction => {
const authorReadTxPromise = session.readTransaction(async (transaction) => {
const authorTransactionResponse = await transaction.run(
`
MATCH (resource {id: $resourceId})<-[:WROTE]-(author {id: $userId})
@ -55,7 +55,7 @@ const isAuthor = rule({
`,
{ resourceId, userId: user.id },
)
return authorTransactionResponse.records.map(record => record.get('author'))
return authorTransactionResponse.records.map((record) => record.get('author'))
})
try {
const [author] = await authorReadTxPromise

View File

@ -1,10 +1,10 @@
import uniqueSlug from './slugify/uniqueSlug'
const isUniqueFor = (context, type) => {
return async slug => {
return async (slug) => {
const session = context.driver.session()
try {
const existingSlug = await session.readTransaction(transaction => {
const existingSlug = await session.readTransaction((transaction) => {
return transaction.run(
`
MATCH(p:${type} {slug: $slug })

View File

@ -9,10 +9,7 @@ describe('uniqueSlug', () => {
it('increments slugified string until unique', () => {
const string = 'Hello World'
const isUnique = jest
.fn()
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
const isUnique = jest.fn().mockResolvedValueOnce(false).mockResolvedValueOnce(true)
expect(uniqueSlug(string, isUnique)).resolves.toEqual('hello-world-1')
})

View File

@ -121,7 +121,7 @@ describe('slugifyMiddleware', () => {
})
describe('but if the client specifies a slug', () => {
it('rejects CreatePost', async done => {
it('rejects CreatePost', async (done) => {
variables = {
...variables,
title: 'Pre-existing post',

View File

@ -17,10 +17,10 @@ const obfuscate = async (resolve, root, args, context, info) => {
root.contentExcerpt = 'UNAVAILABLE'
root.title = 'UNAVAILABLE'
root.slug = 'UNAVAILABLE'
root.avatar = 'UNAVAILABLE'
root.avatar = null
root.about = 'UNAVAILABLE'
root.name = 'UNAVAILABLE'
root.image = null // avoid unecessary 500 errors
root.image = null
}
return resolve(root, args, context, info)
}

View File

@ -28,14 +28,21 @@ beforeAll(async () => {
password: '1234',
},
),
Factory.build('user', {
id: 'u2',
role: 'user',
name: 'Offensive Name',
slug: 'offensive-name',
avatar: '/some/offensive/avatar.jpg',
about: 'This self description is very offensive',
}),
Factory.build(
'user',
{
id: 'u2',
role: 'user',
name: 'Offensive Name',
slug: 'offensive-name',
about: 'This self description is very offensive',
},
{
avatar: Factory.build('image', {
url: '/some/offensive/avatar.jpg',
}),
},
),
neode.create('Category', {
id: 'cat9',
name: 'Democracy & Politics',
@ -96,10 +103,12 @@ beforeAll(async () => {
title: 'Disabled post',
content: 'This is an offensive post content',
contentExcerpt: 'This is an offensive post content',
image: '/some/offensive/image.jpg',
deleted: false,
},
{
image: Factory.build('image', {
url: '/some/offensive/image.jpg',
}),
author: troll,
categoryIds,
},
@ -213,7 +222,9 @@ describe('softDeleteMiddleware', () => {
name
slug
about
avatar
avatar {
url
}
}
}
}
@ -229,7 +240,9 @@ describe('softDeleteMiddleware', () => {
contributions {
title
slug
image
image {
url
}
content
contentExcerpt
}
@ -253,7 +266,10 @@ describe('softDeleteMiddleware', () => {
it('displays slug', () => expect(subject.slug).toEqual('offensive-name'))
it('displays about', () =>
expect(subject.about).toEqual('This self description is very offensive'))
it('displays avatar', () => expect(subject.avatar).toEqual('/some/offensive/avatar.jpg'))
it('displays avatar', () =>
expect(subject.avatar).toEqual({
url: expect.stringContaining('/some/offensive/avatar.jpg'),
}))
})
describe('Post', () => {
@ -265,7 +281,10 @@ describe('softDeleteMiddleware', () => {
expect(subject.content).toEqual('This is an offensive post content'))
it('displays contentExcerpt', () =>
expect(subject.contentExcerpt).toEqual('This is an offensive post content'))
it('displays image', () => expect(subject.image).toEqual('/some/offensive/image.jpg'))
it('displays image', () =>
expect(subject.image).toEqual({
url: expect.stringContaining('/some/offensive/image.jpg'),
}))
})
describe('Comment', () => {
@ -288,7 +307,7 @@ describe('softDeleteMiddleware', () => {
it('obfuscates name', () => expect(subject.name).toEqual('UNAVAILABLE'))
it('obfuscates slug', () => expect(subject.slug).toEqual('UNAVAILABLE'))
it('obfuscates about', () => expect(subject.about).toEqual('UNAVAILABLE'))
it('obfuscates avatar', () => expect(subject.avatar).toEqual('UNAVAILABLE'))
it('obfuscates avatar', () => expect(subject.avatar).toEqual(null))
})
describe('Post', () => {

View File

@ -14,7 +14,7 @@ const validateCreateComment = async (resolve, root, args, context, info) => {
}
const session = context.driver.session()
try {
const postQueryRes = await session.readTransaction(transaction => {
const postQueryRes = await session.readTransaction((transaction) => {
return transaction.run(
`
MATCH (post:Post {id: $postId})
@ -23,7 +23,7 @@ const validateCreateComment = async (resolve, root, args, context, info) => {
{ postId },
)
})
const [post] = postQueryRes.records.map(record => {
const [post] = postQueryRes.records.map((record) => {
return record.get('post')
})
@ -73,7 +73,7 @@ const validateReview = async (resolve, root, args, context, info) => {
const { user, driver } = context
if (resourceId === user.id) throw new Error('You cannot review yourself!')
const session = driver.session()
const reportReadTxPromise = session.readTransaction(async transaction => {
const reportReadTxPromise = session.readTransaction(async (transaction) => {
const validateReviewTransactionResponse = await transaction.run(
`
MATCH (resource {id: $resourceId})
@ -87,7 +87,7 @@ const validateReview = async (resolve, root, args, context, info) => {
submitterId: user.id,
},
)
return validateReviewTransactionResponse.records.map(record => ({
return validateReviewTransactionResponse.records.map((record) => ({
label: record.get('label'),
author: record.get('author'),
filed: record.get('filed'),

View File

@ -0,0 +1,7 @@
export default {
url: { primary: true, type: 'string', uri: { allowRelative: true } },
alt: { type: 'string' },
sensitive: { type: 'boolean', default: false },
aspectRatio: { type: 'float', default: 1.0 },
createdAt: { type: 'string', isoDate: true, default: () => new Date().toISOString() },
}

View File

@ -4,6 +4,12 @@ export default {
id: { type: 'string', primary: true, default: uuid },
activityId: { type: 'string', allow: [null] },
objectId: { type: 'string', allow: [null] },
image: {
type: 'relationship',
relationship: 'HERO_IMAGE',
target: 'Image',
direction: 'out',
},
author: {
type: 'relationship',
relationship: 'WROTE',
@ -14,7 +20,6 @@ export default {
slug: { type: 'string', allow: [null], unique: 'true' },
content: { type: 'string', disallow: [null], min: 3 },
contentExcerpt: { type: 'string', allow: [null] },
image: { type: 'string', allow: [null] },
deleted: { type: 'boolean', default: false },
disabled: { type: 'boolean', default: false },
createdAt: { type: 'string', isoDate: true, default: () => new Date().toISOString() },
@ -25,8 +30,6 @@ export default {
default: () => new Date().toISOString(),
},
language: { type: 'string', allow: [null] },
imageBlurred: { type: 'boolean', default: false },
imageAspectRatio: { type: 'float', default: 1.0 },
comments: {
type: 'relationship',
relationship: 'COMMENTS',

View File

@ -6,8 +6,12 @@ export default {
name: { type: 'string', disallow: [null], min: 3 },
slug: { type: 'string', unique: 'true', regex: /^[a-z0-9_-]+$/, lowercase: true },
encryptedPassword: 'string',
avatar: { type: 'string', allow: [null] },
coverImg: { type: 'string', allow: [null] },
avatar: {
type: 'relationship',
relationship: 'AVATAR_IMAGE',
target: 'Image',
direction: 'out',
},
deleted: { type: 'boolean', default: false },
disabled: { type: 'boolean', default: false },
role: { type: 'string', default: 'user' },

View File

@ -28,7 +28,7 @@ describe('slug', () => {
)
})
it('must be unique', async done => {
it('must be unique', async (done) => {
await neode.create('User', { slug: 'Matt' })
try {
await expect(neode.create('User', { slug: 'Matt' })).rejects.toThrow('already exists')
@ -52,8 +52,8 @@ describe('slug', () => {
})
describe('characters', () => {
const createUser = attrs => {
return neode.create('User', attrs).then(user => user.toJson())
const createUser = (attrs) => {
return neode.create('User', attrs).then((user) => user.toJson())
}
it('-', async () => {

View File

@ -1,6 +1,7 @@
// NOTE: We cannot use `fs` here to clean up the code. Cypress breaks on any npm
// module that is not browser-compatible. Node's `fs` module is server-side only
export default {
Image: require('./Image.js').default,
Badge: require('./Badge.js').default,
User: require('./User.js').default,
EmailAddress: require('./EmailAddress.js').default,

View File

@ -15,7 +15,7 @@ export default {
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const createCommentTransactionResponse = await transaction.run(
`
MATCH (post:Post {id: $postId})
@ -30,7 +30,7 @@ export default {
{ userId: user.id, postId, params },
)
return createCommentTransactionResponse.records.map(
record => record.get('comment').properties,
(record) => record.get('comment').properties,
)
})
try {
@ -42,7 +42,7 @@ export default {
},
UpdateComment: async (_parent, params, context, _resolveInfo) => {
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const updateCommentTransactionResponse = await transaction.run(
`
MATCH (comment:Comment {id: $params.id})
@ -53,7 +53,7 @@ export default {
{ params },
)
return updateCommentTransactionResponse.records.map(
record => record.get('comment').properties,
(record) => record.get('comment').properties,
)
})
try {
@ -65,7 +65,7 @@ export default {
},
DeleteComment: async (_parent, args, context, _resolveInfo) => {
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const deleteCommentTransactionResponse = await transaction.run(
`
MATCH (comment:Comment {id: $commentId})
@ -77,7 +77,7 @@ export default {
{ commentId: args.id },
)
return deleteCommentTransactionResponse.records.map(
record => record.get('comment').properties,
(record) => record.get('comment').properties,
)
})
try {

View File

@ -4,7 +4,7 @@ export default {
const { driver } = context
let donations
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async txc => {
const writeTxResultPromise = session.writeTransaction(async (txc) => {
const updateDonationsTransactionResponse = await txc.run(
`
MATCH (donations:Donations)
@ -16,7 +16,7 @@ export default {
{ params },
)
return updateDonationsTransactionResponse.records.map(
record => record.get('donations').properties,
(record) => record.get('donations').properties,
)
})
try {

View File

@ -27,7 +27,7 @@ export default {
} = context
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async txc => {
const writeTxResultPromise = session.writeTransaction(async (txc) => {
const result = await txc.run(
`
MATCH (user:User {id: $userId})
@ -37,7 +37,7 @@ export default {
`,
{ userId, email: args.email, nonce },
)
return result.records.map(record => ({
return result.records.map((record) => ({
name: record.get('user').properties.name,
...record.get('email').properties,
}))
@ -57,7 +57,7 @@ export default {
} = context
const { nonce, email } = args
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async txc => {
const writeTxResultPromise = session.writeTransaction(async (txc) => {
const result = await txc.run(
`
MATCH (user:User {id: $userId})-[:PRIMARY_EMAIL]->(previous:EmailAddress)
@ -71,7 +71,7 @@ export default {
`,
{ userId, email, nonce },
)
return result.records.map(record => record.get('email').properties)
return result.records.map((record) => record.get('email').properties)
})
try {
const txResult = await writeTxResultPromise

View File

@ -48,7 +48,7 @@ describe('Query', () => {
let embedAction
beforeEach(() => {
embedAction = async variables => {
embedAction = async (variables) => {
const { server } = createServer({
context: () => {},
})

View File

@ -12,11 +12,11 @@ let oEmbedProvidersFile = fs.readFileSync(
oEmbedProvidersFile = oEmbedProvidersFile.replace(/\{format\}/g, 'json')
const oEmbedProviders = JSON.parse(oEmbedProvidersFile)
export default function(embedUrl) {
export default function (embedUrl) {
for (const provider of oEmbedProviders) {
for (const endpoint of provider.endpoints) {
const { schemes = [], url } = endpoint
if (schemes.some(scheme => minimatch(embedUrl, scheme))) return url
if (schemes.some((scheme) => minimatch(embedUrl, scheme))) return url
}
const { hostname } = new URL(embedUrl)
if (provider.provider_url.includes(hostname)) {

View File

@ -29,7 +29,7 @@ const metascraper = Metascraper([
// require('./rules/metascraper-embed')()
])
const fetchEmbed = async url => {
const fetchEmbed = async (url) => {
let endpointUrl = findProvider(url)
if (!endpointUrl) return {}
endpointUrl = new URL(endpointUrl)
@ -53,7 +53,7 @@ const fetchEmbed = async url => {
}
}
const fetchResource = async url => {
const fetchResource = async (url) => {
const response = await fetch(url)
const html = await response.text()
const resource = await metascraper({ html, url })

View File

@ -1,28 +0,0 @@
import { createWriteStream } from 'fs'
import path from 'path'
import slug from 'slug'
import { v4 as uuid } from 'uuid'
const localFileUpload = async ({ createReadStream, uniqueFilename }) => {
await new Promise((resolve, reject) =>
createReadStream()
.pipe(createWriteStream(`public${uniqueFilename}`))
.on('finish', resolve)
.on('error', reject),
)
return uniqueFilename
}
export default async function fileUpload(params, { file, url }, uploadCallback = localFileUpload) {
const upload = params[file]
if (upload) {
const { createReadStream, filename } = await upload
const { name, ext } = path.parse(filename)
const uniqueFilename = `/uploads/${uuid()}-${slug(name)}${ext}`
const location = await uploadCallback({ createReadStream, uniqueFilename })
delete params[file]
params[url] = location
}
return params
}

View File

@ -1,59 +0,0 @@
import fileUpload from '.'
const uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}'
describe('fileUpload', () => {
let params
let uploadCallback
beforeEach(() => {
params = {
uploadAttribute: {
filename: 'avatar.jpg',
mimetype: 'image/jpeg',
encoding: '7bit',
createReadStream: jest.fn(),
},
}
uploadCallback = jest.fn(({ uniqueFilename }) => uniqueFilename)
})
it('calls uploadCallback', async () => {
await fileUpload(params, { file: 'uploadAttribute', url: 'attribute' }, uploadCallback)
expect(uploadCallback).toHaveBeenCalled()
})
describe('file name', () => {
it('saves the upload url in params[url]', async () => {
await fileUpload(params, { file: 'uploadAttribute', url: 'attribute' }, uploadCallback)
expect(params.attribute).toMatch(new RegExp(`^/uploads/${uuid}-avatar.jpg`))
})
it('creates a url safe name', async () => {
params.uploadAttribute.filename = '/path/to/awkward?/ file-location/?foo- bar-avatar.jpg'
await fileUpload(params, { file: 'uploadAttribute', url: 'attribute' }, uploadCallback)
expect(params.attribute).toMatch(new RegExp(`/uploads/${uuid}-foo-bar-avatar.jpg$`))
})
describe('in case of duplicates', () => {
it('creates unique names to avoid overwriting existing files', async () => {
const { attribute: first } = await fileUpload(
{
...params,
},
{ file: 'uploadAttribute', url: 'attribute' },
uploadCallback,
)
const { attribute: second } = await fileUpload(
{
...params,
},
{ file: 'uploadAttribute', url: 'attribute' },
uploadCallback,
)
expect(first).not.toEqual(second)
})
})
})
})

View File

@ -81,7 +81,7 @@ beforeEach(async () => {
email: 'test@example.org',
password: '1234',
},
).then(user => user.toJson())
).then((user) => user.toJson())
user2 = await Factory.build(
'user',
{
@ -92,7 +92,7 @@ beforeEach(async () => {
email: 'test2@example.org',
password: '1234',
},
).then(user => user.toJson())
).then((user) => user.toJson())
authenticatedUser = user1
variables = { id: user2.id }
@ -146,7 +146,7 @@ describe('follow', () => {
{ id: 'u1' },
)
const relationshipProperties = relation.records.map(
record => record.get('relationship').properties.createdAt,
(record) => record.get('relationship').properties.createdAt,
)
expect(relationshipProperties[0]).toEqual(expect.any(String))
})

View File

@ -1,9 +1,9 @@
import log from './databaseLogger'
export const undefinedToNullResolver = list => {
export const undefinedToNullResolver = (list) => {
const resolvers = {}
list.forEach(key => {
resolvers[key] = async parent => {
list.forEach((key) => {
resolvers[key] = async (parent) => {
return typeof parent[key] === 'undefined' ? null : parent[key]
}
})
@ -25,14 +25,14 @@ export default function Resolver(type, options = {}) {
if (typeof parent[key] !== 'undefined') return parent[key]
const id = parent[idAttribute]
const session = driver.session()
const readTxResultPromise = session.readTransaction(async txc => {
const readTxResultPromise = session.readTransaction(async (txc) => {
const cypher = `
MATCH(:${type} {${idAttribute}: $id})${connection}
RETURN related {.*} as related
`
const result = await txc.run(cypher, { id, cypherParams })
log(result)
return result.records.map(r => r.get('related'))
return result.records.map((r) => r.get('related'))
})
try {
let response = await readTxResultPromise
@ -44,19 +44,19 @@ export default function Resolver(type, options = {}) {
}
}
const booleanResolver = obj => {
const booleanResolver = (obj) => {
const resolvers = {}
for (const [key, condition] of Object.entries(obj)) {
resolvers[key] = async (parent, params, { cypherParams, driver }, resolveInfo) => {
if (typeof parent[key] !== 'undefined') return parent[key]
const id = parent[idAttribute]
const session = driver.session()
const readTxResultPromise = session.readTransaction(async txc => {
const readTxResultPromise = session.readTransaction(async (txc) => {
const nodeCondition = condition.replace('this', 'this {id: $id}')
const cypher = `${nodeCondition} as ${key}`
const result = await txc.run(cypher, { id, cypherParams })
log(result)
const [response] = result.records.map(r => r.get(key))
const [response] = result.records.map((r) => r.get(key))
return response
})
try {
@ -69,13 +69,13 @@ export default function Resolver(type, options = {}) {
return resolvers
}
const countResolver = obj => {
const countResolver = (obj) => {
const resolvers = {}
for (const [key, connection] of Object.entries(obj)) {
resolvers[key] = async (parent, params, { driver, cypherParams }, resolveInfo) => {
if (typeof parent[key] !== 'undefined') return parent[key]
const session = driver.session()
const readTxResultPromise = session.readTransaction(async txc => {
const readTxResultPromise = session.readTransaction(async (txc) => {
const id = parent[idAttribute]
const cypher = `
MATCH(u:${type} {${idAttribute}: $id})${connection}
@ -83,7 +83,7 @@ export default function Resolver(type, options = {}) {
`
const result = await txc.run(cypher, { id, cypherParams })
log(result)
const [response] = result.records.map(r => r.get('count').toNumber())
const [response] = result.records.map((r) => r.get('count').toNumber())
return response
})
try {
@ -96,7 +96,7 @@ export default function Resolver(type, options = {}) {
return resolvers
}
const hasManyResolver = obj => {
const hasManyResolver = (obj) => {
const resolvers = {}
for (const [key, connection] of Object.entries(obj)) {
resolvers[key] = _hasResolver(resolvers, { key, connection }, { returnType: 'iterable' })
@ -104,7 +104,7 @@ export default function Resolver(type, options = {}) {
return resolvers
}
const hasOneResolver = obj => {
const hasOneResolver = (obj) => {
const resolvers = {}
for (const [key, connection] of Object.entries(obj)) {
resolvers[key] = _hasResolver(resolvers, { key, connection }, { returnType: 'object' })

View File

@ -5,7 +5,7 @@ export default async function createPasswordReset(options) {
const normalizedEmail = normalizeEmail(email)
const session = driver.session()
try {
const createPasswordResetTxPromise = session.writeTransaction(async transaction => {
const createPasswordResetTxPromise = session.writeTransaction(async (transaction) => {
const createPasswordResetTransactionResponse = await transaction.run(
`
MATCH (user:User)-[:PRIMARY_EMAIL]->(email:EmailAddress {email:$email})
@ -19,7 +19,7 @@ export default async function createPasswordReset(options) {
email: normalizedEmail,
},
)
return createPasswordResetTransactionResponse.records.map(record => {
return createPasswordResetTransactionResponse.records.map((record) => {
const { email } = record.get('email').properties
const { nonce } = record.get('passwordReset').properties
const { name } = record.get('user').properties

View File

@ -3,7 +3,7 @@ import { UserInputError } from 'apollo-server'
export default async function alreadyExistingMail({ args, context }) {
const session = context.driver.session()
try {
const existingEmailAddressTxPromise = session.writeTransaction(async transaction => {
const existingEmailAddressTxPromise = session.writeTransaction(async (transaction) => {
const existingEmailAddressTransactionResponse = await transaction.run(
`
MATCH (email:EmailAddress {email: $email})
@ -12,7 +12,7 @@ export default async function alreadyExistingMail({ args, context }) {
`,
{ email: args.email },
)
return existingEmailAddressTransactionResponse.records.map(record => {
return existingEmailAddressTransactionResponse.records.map((record) => {
return {
alreadyExistingEmail: record.get('email').properties,
user: record.get('user') && record.get('user').properties,

View File

@ -4,7 +4,7 @@ import { mergeWith, isArray } from 'lodash'
export const filterForMutedUsers = async (params, context) => {
if (!context.user) return params
const [mutedUsers] = await Promise.all([getMutedUsers(context)])
const mutedUsersIds = [...mutedUsers.map(user => user.id)]
const mutedUsersIds = [...mutedUsers.map((user) => user.id)]
if (!mutedUsersIds.length) return params
params.filter = mergeWith(

View File

@ -1,6 +1,6 @@
import { normalizeEmail } from 'validator'
export default email =>
export default (email) =>
normalizeEmail(email, {
// gmail_remove_dots: true, default
gmail_remove_subaddress: false,

View File

@ -0,0 +1,8 @@
import Resolver from './helpers/Resolver'
export default {
Image: {
...Resolver('Image', {
undefinedToNull: ['sensitive', 'alt', 'aspectRatio'],
}),
},
}

View File

@ -0,0 +1,153 @@
import path from 'path'
import { v4 as uuid } from 'uuid'
import { S3 } from 'aws-sdk'
import slug from 'slug'
import { existsSync, unlinkSync, createWriteStream } from 'fs'
import { UserInputError } from 'apollo-server'
import { getDriver } from '../../../db/neo4j'
import { s3Configs } from '../../../config'
// const widths = [34, 160, 320, 640, 1024]
const { AWS_ENDPOINT: endpoint, AWS_REGION: region, AWS_BUCKET: Bucket, S3_CONFIGURED } = s3Configs
export async function deleteImage(resource, relationshipType, opts = {}) {
sanitizeRelationshipType(relationshipType)
const { transaction, deleteCallback } = opts
if (!transaction) return wrapTransaction(deleteImage, [resource, relationshipType], opts)
const txResult = await transaction.run(
`
MATCH (resource {id: $resource.id})-[rel:${relationshipType}]->(image:Image)
WITH image, image {.*} as imageProps
DETACH DELETE image
RETURN imageProps
`,
{ resource },
)
const [image] = txResult.records.map((record) => record.get('imageProps'))
// This behaviour differs from `mergeImage`. If you call `mergeImage`
// with metadata for an image that does not exist, it's an indicator
// of an error (so throw an error). If we bulk delete an image, it
// could very well be that there is no image for the resource.
if (image) deleteImageFile(image, deleteCallback)
return image
}
export async function mergeImage(resource, relationshipType, imageInput, opts = {}) {
if (typeof imageInput === 'undefined') return
if (imageInput === null) return deleteImage(resource, relationshipType, opts)
sanitizeRelationshipType(relationshipType)
const { transaction, uploadCallback, deleteCallback } = opts
if (!transaction)
return wrapTransaction(mergeImage, [resource, relationshipType, imageInput], opts)
let txResult
txResult = await transaction.run(
`
MATCH (resource {id: $resource.id})-[:${relationshipType}]->(image:Image)
RETURN image {.*}
`,
{ resource },
)
const [existingImage] = txResult.records.map((record) => record.get('image'))
const { upload } = imageInput
if (!(existingImage || upload)) throw new UserInputError('Cannot find image for given resource')
if (existingImage && upload) deleteImageFile(existingImage, deleteCallback)
const url = await uploadImageFile(upload, uploadCallback)
const { alt, sensitive, aspectRatio } = imageInput
const image = { alt, sensitive, aspectRatio, url }
txResult = await transaction.run(
`
MATCH (resource {id: $resource.id})
MERGE (resource)-[:${relationshipType}]->(image:Image)
ON CREATE SET image.createdAt = toString(datetime())
ON MATCH SET image.updatedAt = toString(datetime())
SET image += $image
RETURN image {.*}
`,
{ resource, image },
)
const [mergedImage] = txResult.records.map((record) => record.get('image'))
return mergedImage
}
const wrapTransaction = async (wrappedCallback, args, opts) => {
const session = getDriver().session()
try {
const result = await session.writeTransaction(async (transaction) => {
return wrappedCallback(...args, { ...opts, transaction })
})
return result
} finally {
session.close()
}
}
const deleteImageFile = (image, deleteCallback) => {
if (!deleteCallback) {
deleteCallback = S3_CONFIGURED ? s3Delete : localFileDelete
}
const { url } = image
deleteCallback(url)
return url
}
const uploadImageFile = async (upload, uploadCallback) => {
if (!upload) return undefined
if (!uploadCallback) {
uploadCallback = S3_CONFIGURED ? s3Upload : localFileUpload
}
const { createReadStream, filename, mimetype } = await upload
const { name, ext } = path.parse(filename)
const uniqueFilename = `${uuid()}-${slug(name)}${ext}`
return uploadCallback({ createReadStream, uniqueFilename, mimetype })
}
const sanitizeRelationshipType = (relationshipType) => {
// Cypher query language does not allow to parameterize relationship types
// See: https://github.com/neo4j/neo4j/issues/340
if (!['HERO_IMAGE', 'AVATAR_IMAGE'].includes(relationshipType)) {
throw new Error(`Unknown relationship type ${relationshipType}`)
}
}
const localFileUpload = ({ createReadStream, uniqueFilename }) => {
const destination = `/uploads/${uniqueFilename}`
return new Promise((resolve, reject) =>
createReadStream()
.pipe(createWriteStream(`public${destination}`))
.on('finish', () => resolve(destination))
.on('error', reject),
)
}
const s3Upload = async ({ createReadStream, uniqueFilename, mimetype }) => {
const s3 = new S3({ region, endpoint })
const s3Location = `original/${uniqueFilename}`
const params = {
Bucket,
Key: s3Location,
ACL: 'public-read',
ContentType: mimetype,
Body: createReadStream(),
}
const data = await s3.upload(params).promise()
const { Location } = data
return Location
}
const localFileDelete = async (url) => {
const location = `public${url}`
if (existsSync(location)) unlinkSync(location)
}
const s3Delete = async (url) => {
const s3 = new S3({ region, endpoint })
let { pathname } = new URL(url, 'http://example.org') // dummy domain to avoid invalid URL error
pathname = pathname.substring(1) // remove first character '/'
const params = {
Bucket,
Key: pathname,
}
await s3.deleteObject(params).promise()
}

View File

@ -0,0 +1,344 @@
import { deleteImage, mergeImage } from './images'
import { getNeode, getDriver } from '../../../db/neo4j'
import Factory, { cleanDatabase } from '../../../db/factories'
import { UserInputError } from 'apollo-server'
const driver = getDriver()
const neode = getNeode()
const uuid = '[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}'
let uploadCallback
let deleteCallback
beforeEach(async () => {
await cleanDatabase()
uploadCallback = jest.fn(({ uniqueFilename }) => `/uploads/${uniqueFilename}`)
deleteCallback = jest.fn()
})
describe('deleteImage', () => {
describe('given a resource with an image', () => {
let user
beforeEach(async () => {
user = await Factory.build(
'user',
{},
{
avatar: Factory.build('image', {
url: '/some/avatar/url/',
alt: 'This is the avatar image of a user',
}),
},
)
user = await user.toJson()
})
it('soft deletes `Image` node', async () => {
await expect(neode.all('Image')).resolves.toHaveLength(1)
await deleteImage(user, 'AVATAR_IMAGE', { deleteCallback })
await expect(neode.all('Image')).resolves.toHaveLength(0)
})
it('calls deleteCallback', async () => {
user = await Factory.build('user')
user = await user.toJson()
await deleteImage(user, 'AVATAR_IMAGE', { deleteCallback })
expect(deleteCallback).toHaveBeenCalled()
})
describe('given a transaction parameter', () => {
it('executes cypher statements within the transaction', async () => {
const session = driver.session()
let someString
try {
someString = await session.writeTransaction(async (transaction) => {
await deleteImage(user, 'AVATAR_IMAGE', {
deleteCallback,
transaction,
})
const txResult = await transaction.run('RETURN "Hello" as result')
const [result] = txResult.records.map((record) => record.get('result'))
return result
})
} finally {
session.close()
}
await expect(neode.all('Image')).resolves.toHaveLength(0)
await expect(someString).toEqual('Hello')
})
it('rolls back the transaction in case of errors', async (done) => {
await expect(neode.all('Image')).resolves.toHaveLength(1)
const session = driver.session()
try {
await session.writeTransaction(async (transaction) => {
await deleteImage(user, 'AVATAR_IMAGE', {
deleteCallback,
transaction,
})
throw new Error('Ouch!')
})
} catch (err) {
// nothing has been deleted
await expect(neode.all('Image')).resolves.toHaveLength(1)
// all good
done()
} finally {
session.close()
}
})
})
})
})
describe('mergeImage', () => {
let imageInput
let post
beforeEach(() => {
imageInput = {
alt: 'A description of the new image',
}
})
describe('given image.upload', () => {
beforeEach(() => {
imageInput = {
...imageInput,
upload: {
filename: 'image.jpg',
mimetype: 'image/jpeg',
encoding: '7bit',
createReadStream: () => ({
pipe: () => ({
on: (_, callback) => callback(),
}),
}),
},
}
})
describe('on existing resource', () => {
beforeEach(async () => {
post = await Factory.build(
'post',
{ id: 'p99' },
{
author: Factory.build('user', {}, { avatar: null }),
image: null,
},
)
post = await post.toJson()
})
it('returns new image', async () => {
await expect(
mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }),
).resolves.toMatchObject({
url: expect.any(String),
alt: 'A description of the new image',
})
})
it('calls upload callback', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
expect(uploadCallback).toHaveBeenCalled()
})
it('creates `:Image` node', async () => {
await expect(neode.all('Image')).resolves.toHaveLength(0)
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
await expect(neode.all('Image')).resolves.toHaveLength(1)
})
it('creates a url safe name', async () => {
imageInput.upload.filename = '/path/to/awkward?/ file-location/?foo- bar-avatar.jpg'
await expect(
mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }),
).resolves.toMatchObject({
url: expect.stringMatching(new RegExp(`^/uploads/${uuid}-foo-bar-avatar.jpg`)),
})
})
it.skip('automatically creates different image sizes', async () => {
await expect(
mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback }),
).resolves.toEqual({
url: expect.any(String),
alt: expect.any(String),
urlW34: expect.stringMatching(new RegExp(`^/uploads/W34/${uuid}-image.jpg`)),
urlW160: expect.stringMatching(new RegExp(`^/uploads/W160/${uuid}-image.jpg`)),
urlW320: expect.stringMatching(new RegExp(`^/uploads/W320/${uuid}-image.jpg`)),
urlW640: expect.stringMatching(new RegExp(`^/uploads/W640/${uuid}-image.jpg`)),
urlW1024: expect.stringMatching(new RegExp(`^/uploads/W1024/${uuid}-image.jpg`)),
})
})
it('connects resource with image via given image type', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
const result = await neode.cypher(`
MATCH(p:Post {id: "p99"})-[:HERO_IMAGE]->(i:Image) RETURN i,p
`)
post = neode.hydrateFirst(result, 'p', neode.model('Post'))
const image = neode.hydrateFirst(result, 'i', neode.model('Image'))
expect(post).toBeTruthy()
expect(image).toBeTruthy()
})
it('whitelists relationship types', async () => {
await expect(
mergeImage(post, 'WHATEVER', imageInput, { uploadCallback, deleteCallback }),
).rejects.toEqual(new Error('Unknown relationship type WHATEVER'))
})
it('sets metadata', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
const image = await neode.first('Image', {})
await expect(image.toJson()).resolves.toMatchObject({
alt: 'A description of the new image',
createdAt: expect.any(String),
url: expect.any(String),
})
})
describe('given a transaction parameter', () => {
it('executes cypher statements within the transaction', async () => {
const session = driver.session()
try {
await session.writeTransaction(async (transaction) => {
const image = await mergeImage(post, 'HERO_IMAGE', imageInput, {
uploadCallback,
deleteCallback,
transaction,
})
return transaction.run(
`
MATCH(image:Image {url: $image.url})
SET image.alt = 'This alt text gets overwritten'
RETURN image {.*}
`,
{ image },
)
})
} finally {
session.close()
}
const image = await neode.first('Image', { alt: 'This alt text gets overwritten' })
await expect(image.toJson()).resolves.toMatchObject({
alt: 'This alt text gets overwritten',
})
})
it('rolls back the transaction in case of errors', async (done) => {
const session = driver.session()
try {
await session.writeTransaction(async (transaction) => {
const image = await mergeImage(post, 'HERO_IMAGE', imageInput, {
uploadCallback,
deleteCallback,
transaction,
})
return transaction.run('Ooops invalid cypher!', { image })
})
} catch (err) {
// nothing has been created
await expect(neode.all('Image')).resolves.toHaveLength(0)
// all good
done()
} finally {
session.close()
}
})
})
describe('if resource has an image already', () => {
beforeEach(async () => {
const [post, image] = await Promise.all([
neode.find('Post', 'p99'),
Factory.build('image'),
])
await post.relateTo(image, 'image')
})
it('calls deleteCallback', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
expect(deleteCallback).toHaveBeenCalled()
})
it('calls uploadCallback', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
expect(uploadCallback).toHaveBeenCalled()
})
it('updates metadata of existing image node', async () => {
await expect(neode.all('Image')).resolves.toHaveLength(1)
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
await expect(neode.all('Image')).resolves.toHaveLength(1)
const image = await neode.first('Image', {})
await expect(image.toJson()).resolves.toMatchObject({
alt: 'A description of the new image',
createdAt: expect.any(String),
url: expect.any(String),
// TODO
// width:
// height:
})
})
})
})
})
describe('without image.upload', () => {
it('throws UserInputError', async () => {
post = await Factory.build('post', { id: 'p99' }, { image: null })
post = await post.toJson()
await expect(mergeImage(post, 'HERO_IMAGE', imageInput)).rejects.toEqual(
new UserInputError('Cannot find image for given resource'),
)
})
describe('if resource has an image already', () => {
beforeEach(async () => {
post = await Factory.build(
'post',
{
id: 'p99',
},
{
author: Factory.build(
'user',
{},
{
avatar: null,
},
),
image: Factory.build('image', {
alt: 'This is the previous, not updated image',
url: '/some/original/url',
}),
},
)
post = await post.toJson()
})
it('does not call deleteCallback', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
expect(deleteCallback).not.toHaveBeenCalled()
})
it('does not call uploadCallback', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
expect(uploadCallback).not.toHaveBeenCalled()
})
it('updates metadata', async () => {
await mergeImage(post, 'HERO_IMAGE', imageInput, { uploadCallback, deleteCallback })
const images = await neode.all('Image')
expect(images).toHaveLength(1)
await expect(images.first().toJson()).resolves.toMatchObject({
createdAt: expect.any(String),
url: expect.any(String),
alt: 'A description of the new image',
})
})
})
})
})

View File

@ -21,14 +21,14 @@ export default {
WITH review, report, resource {.*, __typename: labels(resource)[0]} AS finalResource
RETURN review {.*, report: properties(report), resource: properties(finalResource)}
`
const reviewWriteTxResultPromise = session.writeTransaction(async txc => {
const reviewWriteTxResultPromise = session.writeTransaction(async (txc) => {
const reviewTransactionResponse = await txc.run(cypher, {
params,
moderatorId: moderator.id,
dateTime: new Date().toISOString(),
})
log(reviewTransactionResponse)
return reviewTransactionResponse.records.map(record => record.get('review'))
return reviewTransactionResponse.records.map((record) => record.get('review'))
})
const [reviewed] = await reviewWriteTxResultPromise
return reviewed || null

View File

@ -158,7 +158,7 @@ export default {
markAsRead: async (_parent, args, context, _resolveInfo) => {
const { user: currentUser } = context
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const markNotificationAsReadTransactionResponse = await transaction.run(
`
MATCH (resource {id: $resourceId})-[notification:NOTIFIED {read: FALSE}]->(user:User {id: $id})
@ -172,7 +172,7 @@ export default {
},
)
log(markNotificationAsReadTransactionResponse)
return markNotificationAsReadTransactionResponse.records.map(record =>
return markNotificationAsReadTransactionResponse.records.map((record) =>
record.get('notification'),
)
})
@ -185,7 +185,7 @@ export default {
},
},
NOTIFIED: {
id: async parent => {
id: async (parent) => {
// serialize an ID to help the client update the cache
return `${parent.reason}/${parent.from.id}/${parent.to.id}`
},

View File

@ -14,7 +14,7 @@ export default {
const encryptedNewPassword = await bcrypt.hashSync(newPassword, 10)
const session = driver.session()
try {
const passwordResetTxPromise = session.writeTransaction(async transaction => {
const passwordResetTxPromise = session.writeTransaction(async (transaction) => {
const passwordResetTransactionResponse = await transaction.run(
`
MATCH (passwordReset:PasswordReset {nonce: $nonce})
@ -32,7 +32,9 @@ export default {
encryptedNewPassword,
},
)
return passwordResetTransactionResponse.records.map(record => record.get('passwordReset'))
return passwordResetTransactionResponse.records.map((record) =>
record.get('passwordReset'),
)
})
const [reset] = await passwordResetTxPromise
return !!(reset && reset.properties.usedAt)

View File

@ -16,7 +16,7 @@ const getAllPasswordResets = async () => {
const passwordResetQuery = await neode.cypher(
'MATCH (passwordReset:PasswordReset) RETURN passwordReset',
)
const resets = passwordResetQuery.records.map(record => record.get('passwordReset'))
const resets = passwordResetQuery.records.map((record) => record.get('passwordReset'))
return resets
}

View File

@ -2,11 +2,11 @@ import { v4 as uuid } from 'uuid'
import { neo4jgraphql } from 'neo4j-graphql-js'
import { isEmpty } from 'lodash'
import { UserInputError } from 'apollo-server'
import fileUpload from './fileUpload'
import { mergeImage, deleteImage } from './images/images'
import Resolver from './helpers/Resolver'
import { filterForMutedUsers } from './helpers/filterForMutedUsers'
const maintainPinnedPosts = params => {
const maintainPinnedPosts = (params) => {
const pinnedPostFilter = { pinned: true }
if (isEmpty(params.filter)) {
params.filter = { OR: [pinnedPostFilter, {}] }
@ -34,7 +34,7 @@ export default {
PostsEmotionsCountByEmotion: async (object, params, context, resolveInfo) => {
const { postId, data } = params
const session = context.driver.session()
const readTxResultPromise = session.readTransaction(async transaction => {
const readTxResultPromise = session.readTransaction(async (transaction) => {
const emotionsCountTransactionResponse = await transaction.run(
`
MATCH (post:Post {id: $postId})<-[emoted:EMOTED {emotion: $data.emotion}]-()
@ -43,7 +43,7 @@ export default {
{ postId, data },
)
return emotionsCountTransactionResponse.records.map(
record => record.get('emotionsCount').low,
(record) => record.get('emotionsCount').low,
)
})
try {
@ -56,7 +56,7 @@ export default {
PostsEmotionsByCurrentUser: async (object, params, context, resolveInfo) => {
const { postId } = params
const session = context.driver.session()
const readTxResultPromise = session.readTransaction(async transaction => {
const readTxResultPromise = session.readTransaction(async (transaction) => {
const emotionsTransactionResponse = await transaction.run(
`
MATCH (user:User {id: $userId})-[emoted:EMOTED]->(post:Post {id: $postId})
@ -64,7 +64,7 @@ export default {
`,
{ userId: context.user.id, postId },
)
return emotionsTransactionResponse.records.map(record => record.get('emotion'))
return emotionsTransactionResponse.records.map((record) => record.get('emotion'))
})
try {
const [emotions] = await readTxResultPromise
@ -77,14 +77,16 @@ export default {
Mutation: {
CreatePost: async (_parent, params, context, _resolveInfo) => {
const { categoryIds } = params
const { image: imageInput } = params
delete params.categoryIds
params = await fileUpload(params, { file: 'imageUpload', url: 'image' })
delete params.image
params.id = params.id || uuid()
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const createPostTransactionResponse = await transaction.run(
`
CREATE (post:Post {params})
CREATE (post:Post)
SET post += $params
SET post.createdAt = toString(datetime())
SET post.updatedAt = toString(datetime())
WITH post
@ -94,14 +96,18 @@ export default {
UNWIND $categoryIds AS categoryId
MATCH (category:Category {id: categoryId})
MERGE (post)-[:CATEGORIZED]->(category)
RETURN post
RETURN post {.*}
`,
{ userId: context.user.id, categoryIds, params },
)
return createPostTransactionResponse.records.map(record => record.get('post').properties)
const [post] = createPostTransactionResponse.records.map((record) => record.get('post'))
if (imageInput) {
await mergeImage(post, 'HERO_IMAGE', imageInput, { transaction })
}
return post
})
try {
const [post] = await writeTxResultPromise
const post = await writeTxResultPromise
return post
} catch (e) {
if (e.code === 'Neo.ClientError.Schema.ConstraintValidationFailed')
@ -113,8 +119,9 @@ export default {
},
UpdatePost: async (_parent, params, context, _resolveInfo) => {
const { categoryIds } = params
const { image: imageInput } = params
delete params.categoryIds
params = await fileUpload(params, { file: 'imageUpload', url: 'image' })
delete params.image
const session = context.driver.session()
let updatePostCypher = `
MATCH (post:Post {id: $params.id})
@ -130,7 +137,7 @@ export default {
RETURN post, category
`
await session.writeTransaction(transaction => {
await session.writeTransaction((transaction) => {
return transaction.run(cypherDeletePreviousRelations, { params })
})
@ -142,17 +149,19 @@ export default {
`
}
updatePostCypher += `RETURN post`
updatePostCypher += `RETURN post {.*}`
const updatePostVariables = { categoryIds, params }
try {
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const updatePostTransactionResponse = await transaction.run(
updatePostCypher,
updatePostVariables,
)
return updatePostTransactionResponse.records.map(record => record.get('post').properties)
const [post] = updatePostTransactionResponse.records.map((record) => record.get('post'))
await mergeImage(post, 'HERO_IMAGE', imageInput, { transaction })
return post
})
const [post] = await writeTxResultPromise
const post = await writeTxResultPromise
return post
} finally {
session.close()
@ -161,7 +170,7 @@ export default {
DeletePost: async (object, args, context, resolveInfo) => {
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const deletePostTransactionResponse = await transaction.run(
`
MATCH (post:Post {id: $postId})
@ -171,15 +180,16 @@ export default {
SET post.contentExcerpt = 'UNAVAILABLE'
SET post.title = 'UNAVAILABLE'
SET comment.deleted = TRUE
REMOVE post.image
RETURN post
RETURN post {.*}
`,
{ postId: args.id },
)
return deletePostTransactionResponse.records.map(record => record.get('post').properties)
const [post] = deletePostTransactionResponse.records.map((record) => record.get('post'))
await deleteImage(post, 'HERO_IMAGE', { transaction })
return post
})
try {
const [post] = await writeTxResultPromise
const post = await writeTxResultPromise
return post
} finally {
session.close()
@ -189,7 +199,7 @@ export default {
const { to, data } = params
const { user } = context
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const addPostEmotionsTransactionResponse = await transaction.run(
`
MATCH (userFrom:User {id: $user.id}), (postTo:Post {id: $to.id})
@ -197,7 +207,7 @@ export default {
RETURN userFrom, postTo, emotedRelation`,
{ user, to, data },
)
return addPostEmotionsTransactionResponse.records.map(record => {
return addPostEmotionsTransactionResponse.records.map((record) => {
return {
from: { ...record.get('userFrom').properties },
to: { ...record.get('postTo').properties },
@ -216,7 +226,7 @@ export default {
const { to, data } = params
const { id: from } = context.user
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const removePostEmotionsTransactionResponse = await transaction.run(
`
MATCH (userFrom:User {id: $from})-[emotedRelation:EMOTED {emotion: $data.emotion}]->(postTo:Post {id: $to.id})
@ -225,7 +235,7 @@ export default {
`,
{ from, to, data },
)
return removePostEmotionsTransactionResponse.records.map(record => {
return removePostEmotionsTransactionResponse.records.map((record) => {
return {
from: { ...record.get('userFrom').properties },
to: { ...record.get('postTo').properties },
@ -245,7 +255,7 @@ export default {
const { driver, user } = context
const session = driver.session()
const { id: userId } = user
let writeTxResultPromise = session.writeTransaction(async transaction => {
let writeTxResultPromise = session.writeTransaction(async (transaction) => {
const deletePreviousRelationsResponse = await transaction.run(
`
MATCH (:User)-[previousRelations:PINNED]->(post:Post)
@ -254,12 +264,14 @@ export default {
RETURN post
`,
)
return deletePreviousRelationsResponse.records.map(record => record.get('post').properties)
return deletePreviousRelationsResponse.records.map(
(record) => record.get('post').properties,
)
})
try {
await writeTxResultPromise
writeTxResultPromise = session.writeTransaction(async transaction => {
writeTxResultPromise = session.writeTransaction(async (transaction) => {
const pinPostTransactionResponse = await transaction.run(
`
MATCH (user:User {id: $userId}) WHERE user.role = 'admin'
@ -270,7 +282,7 @@ export default {
`,
{ userId, params },
)
return pinPostTransactionResponse.records.map(record => ({
return pinPostTransactionResponse.records.map((record) => ({
pinnedPost: record.get('post').properties,
pinnedAt: record.get('pinnedAt'),
}))
@ -289,7 +301,7 @@ export default {
unpinPost: async (_parent, params, context, _resolveInfo) => {
let unpinnedPost
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const unpinPostTransactionResponse = await transaction.run(
`
MATCH (:User)-[previousRelations:PINNED]->(post:Post {id: $params.id})
@ -299,7 +311,7 @@ export default {
`,
{ params },
)
return unpinPostTransactionResponse.records.map(record => record.get('post').properties)
return unpinPostTransactionResponse.records.map((record) => record.get('post').properties)
})
try {
;[unpinnedPost] = await writeTxResultPromise
@ -311,16 +323,7 @@ export default {
},
Post: {
...Resolver('Post', {
undefinedToNull: [
'activityId',
'objectId',
'image',
'language',
'pinnedAt',
'pinned',
'imageBlurred',
'imageAspectRatio',
],
undefinedToNull: ['activityId', 'objectId', 'language', 'pinnedAt', 'pinned'],
hasMany: {
tags: '-[:TAGGED]->(related:Tag)',
categories: '-[:CATEGORIZED]->(related:Category)',
@ -331,6 +334,7 @@ export default {
hasOne: {
author: '<-[:WROTE]-(related:User)',
pinnedBy: '<-[:PINNED]-(related:User)',
image: '-[:HERO_IMAGE]->(related:Image)',
},
count: {
commentsCount:
@ -349,7 +353,7 @@ export default {
const { id } = parent
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const relatedContributionsTransactionResponse = await transaction.run(
`
MATCH (p:Post {id: $id})-[:TAGGED|CATEGORIZED]->(categoryOrTag)<-[:TAGGED|CATEGORIZED]-(post:Post)
@ -360,7 +364,7 @@ export default {
{ id },
)
return relatedContributionsTransactionResponse.records.map(
record => record.get('post').properties,
(record) => record.get('post').properties,
)
})
try {

View File

@ -336,8 +336,14 @@ describe('CreatePost', () => {
describe('UpdatePost', () => {
let author, newlyCreatedPost
const updatePostMutation = gql`
mutation($id: ID!, $title: String!, $content: String!, $categoryIds: [ID]) {
UpdatePost(id: $id, title: $title, content: $content, categoryIds: $categoryIds) {
mutation($id: ID!, $title: String!, $content: String!, $categoryIds: [ID], $image: ImageInput) {
UpdatePost(
id: $id
title: $title
content: $content
categoryIds: $categoryIds
image: $image
) {
id
title
content
@ -472,418 +478,471 @@ describe('UpdatePost', () => {
)
})
})
describe('params.image', () => {
describe('is object', () => {
beforeEach(() => {
variables = { ...variables, image: { sensitive: true } }
})
it('updates the image', async () => {
await expect(neode.first('Image', { sensitive: true })).resolves.toBeFalsy()
await mutate({ mutation: updatePostMutation, variables })
await expect(neode.first('Image', { sensitive: true })).resolves.toBeTruthy()
})
})
describe('is null', () => {
beforeEach(() => {
variables = { ...variables, image: null }
})
it('deletes the image', async () => {
await expect(neode.all('Image')).resolves.toHaveLength(6)
await mutate({ mutation: updatePostMutation, variables })
await expect(neode.all('Image')).resolves.toHaveLength(5)
})
})
describe('is undefined', () => {
beforeEach(() => {
delete variables.image
})
it('keeps the image unchanged', async () => {
await expect(neode.first('Image', { sensitive: true })).resolves.toBeFalsy()
await mutate({ mutation: updatePostMutation, variables })
await expect(neode.first('Image', { sensitive: true })).resolves.toBeFalsy()
})
})
})
})
})
describe('pin posts', () => {
let author
const pinPostMutation = gql`
mutation($id: ID!) {
pinPost(id: $id) {
id
title
content
author {
name
slug
}
pinnedBy {
id
name
role
}
createdAt
updatedAt
pinnedAt
pinned
}
}
`
beforeEach(async () => {
author = await Factory.build('user', { slug: 'the-author' })
await Factory.build(
'post',
{
id: 'p9876',
title: 'Old title',
content: 'Old content',
},
{
author,
categoryIds,
},
)
variables = {
id: 'p9876',
}
})
describe('pin posts', () => {
const pinPostMutation = gql`
mutation($id: ID!) {
pinPost(id: $id) {
id
title
content
author {
name
slug
}
pinnedBy {
id
name
role
}
createdAt
updatedAt
pinnedAt
pinned
}
}
`
describe('unauthenticated', () => {
it('throws authorization error', async () => {
authenticatedUser = null
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { pinPost: null },
})
})
})
describe('ordinary users', () => {
it('throws authorization error', async () => {
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { pinPost: null },
})
})
})
describe('moderators', () => {
let moderator
beforeEach(async () => {
variables = { ...variables }
moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() })
authenticatedUser = await moderator.toJson()
})
describe('unauthenticated', () => {
it('throws authorization error', async () => {
authenticatedUser = null
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { pinPost: null },
})
it('throws authorization error', async () => {
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { pinPost: null },
})
})
})
describe('ordinary users', () => {
it('throws authorization error', async () => {
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { pinPost: null },
})
describe('admins', () => {
let admin
beforeEach(async () => {
admin = await user.update({
role: 'admin',
name: 'Admin',
updatedAt: new Date().toISOString(),
})
authenticatedUser = await admin.toJson()
})
describe('moderators', () => {
let moderator
describe('are allowed to pin posts', () => {
beforeEach(async () => {
moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() })
authenticatedUser = await moderator.toJson()
await Factory.build(
'post',
{
id: 'created-and-pinned-by-same-admin',
},
{
author: admin,
},
)
variables = { ...variables, id: 'created-and-pinned-by-same-admin' }
})
it('throws authorization error', async () => {
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { pinPost: null },
})
})
})
describe('admins', () => {
let admin
beforeEach(async () => {
admin = await user.update({
role: 'admin',
name: 'Admin',
updatedAt: new Date().toISOString(),
})
authenticatedUser = await admin.toJson()
})
describe('are allowed to pin posts', () => {
beforeEach(async () => {
await Factory.build(
'post',
{
it('responds with the updated Post', async () => {
const expected = {
data: {
pinPost: {
id: 'created-and-pinned-by-same-admin',
},
{
author: admin,
},
)
variables = { ...variables, id: 'created-and-pinned-by-same-admin' }
})
it('responds with the updated Post', async () => {
const expected = {
data: {
pinPost: {
id: 'created-and-pinned-by-same-admin',
author: {
name: 'Admin',
},
pinnedBy: {
id: 'current-user',
name: 'Admin',
role: 'admin',
},
author: {
name: 'Admin',
},
pinnedBy: {
id: 'current-user',
name: 'Admin',
role: 'admin',
},
},
errors: undefined,
}
},
errors: undefined,
}
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
it('sets createdAt date for PINNED', async () => {
const expected = {
data: {
pinPost: {
id: 'created-and-pinned-by-same-admin',
pinnedAt: expect.any(String),
},
},
errors: undefined,
}
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
it('sets redundant `pinned` property for performant ordering', async () => {
variables = { ...variables, id: 'created-and-pinned-by-same-admin' }
const expected = {
data: { pinPost: { pinned: true } },
errors: undefined,
}
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
describe('post created by another admin', () => {
let otherAdmin
beforeEach(async () => {
otherAdmin = await Factory.build('user', {
role: 'admin',
name: 'otherAdmin',
})
authenticatedUser = await otherAdmin.toJson()
await Factory.build(
'post',
{
it('sets createdAt date for PINNED', async () => {
const expected = {
data: {
pinPost: {
id: 'created-and-pinned-by-same-admin',
pinnedAt: expect.any(String),
},
},
errors: undefined,
}
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
it('sets redundant `pinned` property for performant ordering', async () => {
variables = { ...variables, id: 'created-and-pinned-by-same-admin' }
const expected = {
data: { pinPost: { pinned: true } },
errors: undefined,
}
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
})
describe('post created by another admin', () => {
let otherAdmin
beforeEach(async () => {
otherAdmin = await Factory.build('user', {
role: 'admin',
name: 'otherAdmin',
})
authenticatedUser = await otherAdmin.toJson()
await Factory.build(
'post',
{
id: 'created-by-one-admin-pinned-by-different-one',
},
{
author: otherAdmin,
},
)
})
it('responds with the updated Post', async () => {
authenticatedUser = await admin.toJson()
variables = { ...variables, id: 'created-by-one-admin-pinned-by-different-one' }
const expected = {
data: {
pinPost: {
id: 'created-by-one-admin-pinned-by-different-one',
},
{
author: otherAdmin,
},
)
})
it('responds with the updated Post', async () => {
authenticatedUser = await admin.toJson()
variables = { ...variables, id: 'created-by-one-admin-pinned-by-different-one' }
const expected = {
data: {
pinPost: {
id: 'created-by-one-admin-pinned-by-different-one',
author: {
name: 'otherAdmin',
},
pinnedBy: {
id: 'current-user',
name: 'Admin',
role: 'admin',
},
author: {
name: 'otherAdmin',
},
pinnedBy: {
id: 'current-user',
name: 'Admin',
role: 'admin',
},
},
errors: undefined,
}
},
errors: undefined,
}
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
})
describe('post created by another user', () => {
it('responds with the updated Post', async () => {
const expected = {
data: {
pinPost: {
id: 'p9876',
author: {
slug: 'the-author',
},
pinnedBy: {
id: 'current-user',
name: 'Admin',
role: 'admin',
},
describe('post created by another user', () => {
it('responds with the updated Post', async () => {
const expected = {
data: {
pinPost: {
id: 'p9876',
author: {
slug: 'the-author',
},
pinnedBy: {
id: 'current-user',
name: 'Admin',
role: 'admin',
},
},
errors: undefined,
}
},
errors: undefined,
}
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
await expect(mutate({ mutation: pinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
})
describe('pinned post already exists', () => {
let pinnedPost
beforeEach(async () => {
await Factory.build(
'post',
{
id: 'only-pinned-post',
},
{
author: admin,
},
)
await mutate({ mutation: pinPostMutation, variables })
})
it('removes previous `pinned` attribute', async () => {
const cypher = 'MATCH (post:Post) WHERE post.pinned IS NOT NULL RETURN post'
pinnedPost = await neode.cypher(cypher)
expect(pinnedPost.records).toHaveLength(1)
variables = { ...variables, id: 'only-pinned-post' }
await mutate({ mutation: pinPostMutation, variables })
pinnedPost = await neode.cypher(cypher)
expect(pinnedPost.records).toHaveLength(1)
})
it('removes previous PINNED relationship', async () => {
variables = { ...variables, id: 'only-pinned-post' }
await mutate({ mutation: pinPostMutation, variables })
pinnedPost = await neode.cypher(
`MATCH (:User)-[pinned:PINNED]->(post:Post) RETURN post, pinned`,
)
expect(pinnedPost.records).toHaveLength(1)
})
})
describe('PostOrdering', () => {
beforeEach(async () => {
await Factory.build('post', {
id: 'im-a-pinned-post',
createdAt: '2019-11-22T17:26:29.070Z',
pinned: true,
})
await Factory.build('post', {
id: 'i-was-created-before-pinned-post',
// fairly old, so this should be 3rd
createdAt: '2019-10-22T17:26:29.070Z',
})
})
describe('pinned post already exists', () => {
let pinnedPost
beforeEach(async () => {
await Factory.build(
'post',
{
id: 'only-pinned-post',
},
{
author: admin,
},
)
await mutate({ mutation: pinPostMutation, variables })
describe('order by `pinned_asc` and `createdAt_desc`', () => {
beforeEach(() => {
// this is the ordering in the frontend
variables = { orderBy: ['pinned_asc', 'createdAt_desc'] }
})
it('removes previous `pinned` attribute', async () => {
const cypher = 'MATCH (post:Post) WHERE post.pinned IS NOT NULL RETURN post'
pinnedPost = await neode.cypher(cypher)
expect(pinnedPost.records).toHaveLength(1)
variables = { ...variables, id: 'only-pinned-post' }
await mutate({ mutation: pinPostMutation, variables })
pinnedPost = await neode.cypher(cypher)
expect(pinnedPost.records).toHaveLength(1)
})
it('removes previous PINNED relationship', async () => {
variables = { ...variables, id: 'only-pinned-post' }
await mutate({ mutation: pinPostMutation, variables })
pinnedPost = await neode.cypher(
`MATCH (:User)-[pinned:PINNED]->(post:Post) RETURN post, pinned`,
)
expect(pinnedPost.records).toHaveLength(1)
})
})
describe('PostOrdering', () => {
beforeEach(async () => {
await Factory.build('post', {
id: 'im-a-pinned-post',
createdAt: '2019-11-22T17:26:29.070Z',
pinned: true,
})
await Factory.build('post', {
id: 'i-was-created-before-pinned-post',
// fairly old, so this should be 3rd
createdAt: '2019-10-22T17:26:29.070Z',
})
})
describe('order by `pinned_asc` and `createdAt_desc`', () => {
beforeEach(() => {
// this is the ordering in the frontend
variables = { orderBy: ['pinned_asc', 'createdAt_desc'] }
})
it('pinned post appear first even when created before other posts', async () => {
const postOrderingQuery = gql`
query($orderBy: [_PostOrdering]) {
Post(orderBy: $orderBy) {
id
pinned
createdAt
pinnedAt
}
it('pinned post appear first even when created before other posts', async () => {
const postOrderingQuery = gql`
query($orderBy: [_PostOrdering]) {
Post(orderBy: $orderBy) {
id
pinned
createdAt
pinnedAt
}
`
await expect(query({ query: postOrderingQuery, variables })).resolves.toMatchObject({
data: {
Post: [
{
id: 'im-a-pinned-post',
pinned: true,
createdAt: '2019-11-22T17:26:29.070Z',
pinnedAt: expect.any(String),
},
{
id: 'p9876',
pinned: null,
createdAt: expect.any(String),
pinnedAt: null,
},
{
id: 'i-was-created-before-pinned-post',
pinned: null,
createdAt: '2019-10-22T17:26:29.070Z',
pinnedAt: null,
},
],
},
errors: undefined,
})
}
`
await expect(query({ query: postOrderingQuery, variables })).resolves.toMatchObject({
data: {
Post: [
{
id: 'im-a-pinned-post',
pinned: true,
createdAt: '2019-11-22T17:26:29.070Z',
pinnedAt: expect.any(String),
},
{
id: 'p9876',
pinned: null,
createdAt: expect.any(String),
pinnedAt: null,
},
{
id: 'i-was-created-before-pinned-post',
pinned: null,
createdAt: '2019-10-22T17:26:29.070Z',
pinnedAt: null,
},
],
},
errors: undefined,
})
})
})
})
})
})
describe('unpin posts', () => {
const unpinPostMutation = gql`
mutation($id: ID!) {
unpinPost(id: $id) {
describe('unpin posts', () => {
let pinnedPost
const unpinPostMutation = gql`
mutation($id: ID!) {
unpinPost(id: $id) {
id
title
content
author {
name
slug
}
pinnedBy {
id
title
content
author {
name
slug
}
pinnedBy {
id
name
role
}
createdAt
updatedAt
pinned
pinnedAt
name
role
}
createdAt
updatedAt
pinned
pinnedAt
}
`
}
`
beforeEach(async () => {
pinnedPost = await Factory.build('post', { id: 'post-to-be-unpinned' })
variables = {
id: 'post-to-be-unpinned',
}
})
describe('unauthenticated', () => {
it('throws authorization error', async () => {
authenticatedUser = null
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { unpinPost: null },
})
})
})
describe('users cannot unpin posts', () => {
it('throws authorization error', async () => {
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { unpinPost: null },
})
})
})
describe('moderators cannot unpin posts', () => {
let moderator
beforeEach(async () => {
variables = { ...variables }
moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() })
authenticatedUser = await moderator.toJson()
})
describe('unauthenticated', () => {
it('throws authorization error', async () => {
authenticatedUser = null
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { unpinPost: null },
})
it('throws authorization error', async () => {
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { unpinPost: null },
})
})
})
describe('users cannot unpin posts', () => {
it('throws authorization error', async () => {
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { unpinPost: null },
})
describe('admin can unpin posts', () => {
let admin
beforeEach(async () => {
admin = await user.update({
role: 'admin',
name: 'Admin',
updatedAt: new Date().toISOString(),
})
authenticatedUser = await admin.toJson()
await admin.relateTo(pinnedPost, 'pinned', { createdAt: new Date().toISOString() })
})
describe('moderators cannot unpin posts', () => {
let moderator
beforeEach(async () => {
moderator = await user.update({ role: 'moderator', updatedAt: new Date().toISOString() })
authenticatedUser = await moderator.toJson()
})
it('throws authorization error', async () => {
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject({
errors: [{ message: 'Not Authorised!' }],
data: { unpinPost: null },
})
})
})
describe('admin can unpin posts', () => {
let admin, pinnedPost
beforeEach(async () => {
pinnedPost = await Factory.build('post', { id: 'post-to-be-unpinned' })
admin = await user.update({
role: 'admin',
name: 'Admin',
updatedAt: new Date().toISOString(),
})
authenticatedUser = await admin.toJson()
await admin.relateTo(pinnedPost, 'pinned', { createdAt: new Date().toISOString() })
variables = { ...variables, id: 'post-to-be-unpinned' }
})
it('responds with the unpinned Post', async () => {
authenticatedUser = await admin.toJson()
const expected = {
data: {
unpinPost: {
id: 'post-to-be-unpinned',
pinnedBy: null,
pinnedAt: null,
},
it('responds with the unpinned Post', async () => {
authenticatedUser = await admin.toJson()
const expected = {
data: {
unpinPost: {
id: 'post-to-be-unpinned',
pinnedBy: null,
pinnedAt: null,
},
errors: undefined,
}
},
errors: undefined,
}
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
it('unsets `pinned` property', async () => {
const expected = {
data: {
unpinPost: {
id: 'post-to-be-unpinned',
pinned: null,
},
it('unsets `pinned` property', async () => {
const expected = {
data: {
unpinPost: {
id: 'post-to-be-unpinned',
pinned: null,
},
errors: undefined,
}
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
},
errors: undefined,
}
await expect(mutate({ mutation: unpinPostMutation, variables })).resolves.toMatchObject(
expected,
)
})
})
})
@ -897,7 +956,9 @@ describe('DeletePost', () => {
deleted
content
contentExcerpt
image
image {
url
}
comments {
deleted
content
@ -915,9 +976,11 @@ describe('DeletePost', () => {
id: 'p4711',
title: 'I will be deleted',
content: 'To be deleted',
image: 'path/to/some/image',
},
{
image: Factory.build('image', {
url: 'path/to/some/image',
}),
author,
categoryIds,
},

View File

@ -1,11 +1,9 @@
import { UserInputError } from 'apollo-server'
import { getNeode } from '../../db/neo4j'
import fileUpload from './fileUpload'
import encryptPassword from '../../helpers/encryptPassword'
import generateNonce from './helpers/generateNonce'
import existingEmailAddress from './helpers/existingEmailAddress'
import normalizeEmail from './helpers/normalizeEmail'
import createOrUpdateLocations from './users/location'
const neode = getNeode()
@ -24,8 +22,6 @@ export default {
}
},
SignupVerification: async (_parent, args, context) => {
const { driver } = context
const session = driver.session()
const { termsAndConditionsAgreedVersion } = args
const regEx = new RegExp(/^[0-9]+\.[0-9]+\.[0-9]+$/g)
if (!regEx.test(termsAndConditionsAgreedVersion)) {
@ -35,27 +31,39 @@ export default {
let { nonce, email } = args
email = normalizeEmail(email)
const result = await neode.cypher(
`
MATCH(email:EmailAddress {nonce: {nonce}, email: {email}})
WHERE NOT (email)-[:BELONGS_TO]->()
RETURN email
`,
{ nonce, email },
)
const emailAddress = await neode.hydrateFirst(result, 'email', neode.model('EmailAddress'))
if (!emailAddress) throw new UserInputError('Invalid email or nonce')
args = await fileUpload(args, { file: 'avatarUpload', url: 'avatar' })
args = await encryptPassword(args)
delete args.nonce
delete args.email
args = encryptPassword(args)
const { driver } = context
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const createUserTransactionResponse = await transaction.run(
`
MATCH(email:EmailAddress {nonce: $nonce, email: $email})
WHERE NOT (email)-[:BELONGS_TO]->()
CREATE (user:User)
MERGE(user)-[:PRIMARY_EMAIL]->(email)
MERGE(user)<-[:BELONGS_TO]-(email)
SET user += $args
SET user.id = randomUUID()
SET user.role = 'user'
SET user.createdAt = toString(datetime())
SET user.updatedAt = toString(datetime())
SET user.allowEmbedIframes = FALSE
SET user.showShoutsPublicly = FALSE
SET email.verifiedAt = toString(datetime())
RETURN user {.*}
`,
{ args, nonce, email },
)
const [user] = createUserTransactionResponse.records.map((record) => record.get('user'))
if (!user) throw new UserInputError('Invalid email or nonce')
return user
})
try {
const user = await neode.create('User', args)
await Promise.all([
user.relateTo(emailAddress, 'primaryEmail'),
emailAddress.relateTo(user, 'belongsTo'),
emailAddress.update({ verifiedAt: new Date().toISOString() }),
])
await createOrUpdateLocations(args.id, args.locationName, session)
return user.toJson()
const user = await writeTxResultPromise
return user
} catch (e) {
if (e.code === 'Neo.ClientError.Schema.ConstraintValidationFailed')
throw new UserInputError('User with this slug already exists!')

View File

@ -7,7 +7,7 @@ export default {
const { resourceId, reasonCategory, reasonDescription } = params
const { driver, user } = context
const session = driver.session()
const fileReportWriteTxResultPromise = session.writeTransaction(async transaction => {
const fileReportWriteTxResultPromise = session.writeTransaction(async (transaction) => {
const fileReportTransactionResponse = await transaction.run(
`
MATCH (submitter:User {id: $submitterId})
@ -30,7 +30,7 @@ export default {
},
)
log(fileReportTransactionResponse)
return fileReportTransactionResponse.records.map(record => record.get('filedReport'))
return fileReportTransactionResponse.records.map((record) => record.get('filedReport'))
})
try {
const [filedReport] = await fileReportWriteTxResultPromise
@ -82,7 +82,7 @@ export default {
params.offset && typeof params.offset === 'number' ? `SKIP ${params.offset}` : ''
const limit = params.first && typeof params.first === 'number' ? `LIMIT ${params.first}` : ''
const reportsReadTxPromise = session.readTransaction(async transaction => {
const reportsReadTxPromise = session.readTransaction(async (transaction) => {
const reportsTransactionResponse = await transaction.run(
// !!! this Cypher query returns multiple reports on the same resource! i will create an issue for refactoring (bug fixing)
`
@ -103,7 +103,7 @@ export default {
`,
)
log(reportsTransactionResponse)
return reportsTransactionResponse.records.map(record => record.get('report'))
return reportsTransactionResponse.records.map((record) => record.get('report'))
})
try {
const reports = await reportsReadTxPromise
@ -119,7 +119,7 @@ export default {
const session = context.driver.session()
const { id } = parent
let filed
const readTxPromise = session.readTransaction(async transaction => {
const readTxPromise = session.readTransaction(async (transaction) => {
const filedReportsTransactionResponse = await transaction.run(
`
MATCH (submitter:User)-[filed:FILED]->(report:Report {id: $id})
@ -128,14 +128,14 @@ export default {
{ id },
)
log(filedReportsTransactionResponse)
return filedReportsTransactionResponse.records.map(record => ({
return filedReportsTransactionResponse.records.map((record) => ({
submitter: record.get('submitter').properties,
filed: record.get('filed').properties,
}))
})
try {
const filedReports = await readTxPromise
filed = filedReports.map(reportedRecord => {
filed = filedReports.map((reportedRecord) => {
const { submitter, filed } = reportedRecord
const relationshipWithNestedAttributes = {
...filed,
@ -153,7 +153,7 @@ export default {
const session = context.driver.session()
const { id } = parent
let reviewed
const readTxPromise = session.readTransaction(async transaction => {
const readTxPromise = session.readTransaction(async (transaction) => {
const reviewedReportsTransactionResponse = await transaction.run(
`
MATCH (resource)<-[:BELONGS_TO]-(report:Report {id: $id})<-[review:REVIEWED]-(moderator:User)
@ -163,14 +163,14 @@ export default {
{ id },
)
log(reviewedReportsTransactionResponse)
return reviewedReportsTransactionResponse.records.map(record => ({
return reviewedReportsTransactionResponse.records.map((record) => ({
review: record.get('review').properties,
moderator: record.get('moderator').properties,
}))
})
try {
const reviewedReports = await readTxPromise
reviewed = reviewedReports.map(reportedRecord => {
reviewed = reviewedReports.map((reportedRecord) => {
const { review, moderator } = reportedRecord
const relationshipWithNestedAttributes = {
...review,

View File

@ -246,7 +246,7 @@ describe('file a report on a resource', () => {
})
expect(reportsCypherQueryResponse.records).toHaveLength(1)
const [reportProperties] = reportsCypherQueryResponse.records.map(
record => record.get('report').properties,
(record) => record.get('report').properties,
)
expect(reportProperties).toMatchObject({ rule: 'latestReviewUpdatedAtRules' })
})
@ -264,7 +264,7 @@ describe('file a report on a resource', () => {
})
expect(reportsCypherQueryResponse.records).toHaveLength(1)
const [reportProperties] = reportsCypherQueryResponse.records.map(
record => record.get('report').properties,
(record) => record.get('report').properties,
)
expect(reportProperties).toMatchObject({ disable: false })
})
@ -297,7 +297,7 @@ describe('file a report on a resource', () => {
})
expect(reportsCypherQueryResponse.records).toHaveLength(1)
const [reportProperties] = reportsCypherQueryResponse.records.map(
record => record.get('report').properties,
(record) => record.get('report').properties,
)
expect(reportProperties).toMatchObject({ disable: true })
})

View File

@ -24,7 +24,7 @@ export default {
const { user } = await getUserAndBadge(params)
const session = context.driver.session()
try {
await session.writeTransaction(transaction => {
await session.writeTransaction((transaction) => {
return transaction.run(
`
MATCH (badge:Badge {id: $badgeKey})-[reward:REWARDED]->(rewardedUser:User {id: $userId})

View File

@ -1,22 +1,19 @@
import log from './helpers/databaseLogger'
import { queryString } from './searches/queryString'
// see http://lucene.apache.org/core/8_3_1/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description
export default {
Query: {
findResources: async (_parent, args, context, _resolveInfo) => {
const { query, limit } = args
const { id: thisUserId } = context.user
// see http://lucene.apache.org/core/8_3_1/queryparser/org/apache/lucene/queryparser/classic/package-summary.html#package.description
const myQuery = query
.replace(/\s+/g, ' ')
.replace(/[[@#:*~\\$|^\]?/"'(){}+?!,.-;]/g, '')
.split(' ')
.map(s => (s.toLowerCase().match(/^(not|and|or)$/) ? '"' + s + '"' : s + '*'))
.join(' ')
const postCypher = `
CALL db.index.fulltext.queryNodes('post_fulltext_search', $query)
YIELD node as resource, score
MATCH (resource)<-[:WROTE]-(author:User)
WHERE score >= 0.5
WHERE score >= 0.0
AND NOT (
author.deleted = true OR author.disabled = true
OR resource.deleted = true OR resource.disabled = true
@ -39,14 +36,25 @@ export default {
CALL db.index.fulltext.queryNodes('user_fulltext_search', $query)
YIELD node as resource, score
MATCH (resource)
WHERE score >= 0.5
WHERE score >= 0.0
AND NOT (resource.deleted = true OR resource.disabled = true)
RETURN resource {.*, __typename: labels(resource)[0]}
LIMIT $limit
`
const tagCypher = `
CALL db.index.fulltext.queryNodes('tag_fulltext_search', $query)
YIELD node as resource, score
MATCH (resource)
WHERE score >= 0.0
AND NOT (resource.deleted = true OR resource.disabled = true)
RETURN resource {.*, __typename: labels(resource)[0]}
LIMIT $limit
`
const myQuery = queryString(query)
const session = context.driver.session()
const searchResultPromise = session.readTransaction(async transaction => {
const searchResultPromise = session.readTransaction(async (transaction) => {
const postTransactionResponse = transaction.run(postCypher, {
query: myQuery,
limit,
@ -57,14 +65,25 @@ export default {
limit,
thisUserId,
})
return Promise.all([postTransactionResponse, userTransactionResponse])
const tagTransactionResponse = transaction.run(tagCypher, {
query: myQuery,
limit,
})
return Promise.all([
postTransactionResponse,
userTransactionResponse,
tagTransactionResponse,
])
})
try {
const [postResults, userResults] = await searchResultPromise
const [postResults, userResults, tagResults] = await searchResultPromise
log(postResults)
log(userResults)
return [...postResults.records, ...userResults.records].map(r => r.get('resource'))
log(tagResults)
return [...postResults.records, ...userResults.records, ...tagResults.records].map((r) =>
r.get('resource'),
)
} finally {
session.close()
}

View File

@ -0,0 +1,469 @@
import Factory, { cleanDatabase } from '../../db/factories'
import { gql } from '../../helpers/jest'
import { getNeode, getDriver } from '../../db/neo4j'
import createServer from '../../server'
import { createTestClient } from 'apollo-server-testing'
let query, authenticatedUser, user
const driver = getDriver()
const neode = getNeode()
beforeAll(async () => {
await cleanDatabase()
const { server } = createServer({
context: () => {
return {
driver,
neode,
user: authenticatedUser,
}
},
})
query = createTestClient(server).query
})
afterAll(async () => {
await cleanDatabase()
})
const searchQuery = gql`
query($query: String!) {
findResources(query: $query, limit: 5) {
__typename
... on Post {
id
title
content
}
... on User {
id
slug
name
}
... on Tag {
id
}
}
}
`
describe('resolvers/searches', () => {
let variables
describe('given one user', () => {
beforeAll(async () => {
user = await Factory.build('user', {
id: 'a-user',
name: 'John Doe',
slug: 'john-doe',
})
authenticatedUser = await user.toJson()
})
describe('query contains first name of user', () => {
it('finds the user', async () => {
variables = { query: 'John' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
id: 'a-user',
name: 'John Doe',
slug: 'john-doe',
},
],
},
})
})
})
describe('adding one post', () => {
beforeAll(async () => {
await Factory.build(
'post',
{
id: 'a-post',
title: 'Beitrag',
content: 'Ein erster Beitrag',
},
{ authorId: 'a-user' },
)
})
describe('query contains title of post', () => {
it('finds the post', async () => {
variables = { query: 'beitrag' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'a-post',
title: 'Beitrag',
content: 'Ein erster Beitrag',
},
],
},
})
})
})
describe('casing', () => {
it('does not matter', async () => {
variables = { query: 'BEITRAG' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'a-post',
title: 'Beitrag',
content: 'Ein erster Beitrag',
},
],
},
})
})
})
describe('query consists of words not present in the corpus', () => {
it('returns empty search results', async () => {
await expect(
query({ query: searchQuery, variables: { query: 'Unfug' } }),
).resolves.toMatchObject({ data: { findResources: [] } })
})
})
describe('testing different post content', () => {
beforeAll(async () => {
return Promise.all([
Factory.build(
'post',
{
id: 'b-post',
title: 'Aufruf',
content: 'Jeder sollte seinen Beitrag leisten.',
},
{ authorId: 'a-user' },
),
Factory.build(
'post',
{
id: 'g-post',
title: 'Zusammengesetzte Wörter',
content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`,
},
{ authorId: 'a-user' },
),
Factory.build(
'post',
{
id: 'c-post',
title: 'Die binomischen Formeln',
content: `1. binomische Formel: (a + b)² = a² + 2ab + b²
2. binomische Formel: (a - b)² = - 2ab +
3. binomische Formel: (a + b)(a - b) = - `,
},
{ authorId: 'a-user' },
),
Factory.build(
'post',
{
id: 'd-post',
title: 'Der Panther',
content: `Sein Blick ist vom Vorübergehn der Stäbe
so müd geworden, daß er nichts mehr hält.
Ihm ist, als ob es tausend Stäbe gäbe
und hinter tausend Stäben keine Welt.`,
},
{ authorId: 'a-user' },
),
])
})
describe('a post which content contains the title of the first post', () => {
describe('query contains the title of the first post', () => {
it('finds both posts', async () => {
variables = { query: 'beitrag' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: expect.arrayContaining([
{
__typename: 'Post',
id: 'a-post',
title: 'Beitrag',
content: 'Ein erster Beitrag',
},
{
__typename: 'Post',
id: 'b-post',
title: 'Aufruf',
content: 'Jeder sollte seinen Beitrag leisten.',
},
]),
},
})
})
})
})
describe('a post that contains a hyphen between two words and German quotation marks', () => {
describe('hyphens in query', () => {
it('will be treated as ordinary characters', async () => {
variables = { query: 'tee-ei' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'g-post',
title: 'Zusammengesetzte Wörter',
content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`,
},
],
},
})
})
})
describe('German quotation marks in query to test unicode characters (\u201E ... \u201C)', () => {
it('will be treated as ordinary characters', async () => {
variables = { query: '„teeei“' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'g-post',
title: 'Zusammengesetzte Wörter',
content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`,
},
],
},
})
})
})
})
describe('a post that contains a simple mathematical exprssion and line breaks', () => {
describe('query a part of the mathematical expression', () => {
it('finds that post', async () => {
variables = { query: '(a - b)²' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'c-post',
title: 'Die binomischen Formeln',
content: `1. binomische Formel: (a + b)² = a² + 2ab + b²<br>
2. binomische Formel: (a - b)² = - 2ab + <br>
3. binomische Formel: (a + b)(a - b) = - `,
},
],
},
})
})
})
describe('query the same part of the mathematical expression without spaces', () => {
it('finds that post', async () => {
variables = { query: '(a-b)²' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'c-post',
title: 'Die binomischen Formeln',
content: `1. binomische Formel: (a + b)² = a² + 2ab + b²<br>
2. binomische Formel: (a - b)² = - 2ab + <br>
3. binomische Formel: (a + b)(a - b) = - `,
},
],
},
})
})
})
describe('query the mathematical expression over line break', () => {
it('finds that post', async () => {
variables = { query: '+ b² 2.' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'c-post',
title: 'Die binomischen Formeln',
content: `1. binomische Formel: (a + b)² = a² + 2ab + b²<br>
2. binomische Formel: (a - b)² = - 2ab + <br>
3. binomische Formel: (a + b)(a - b) = - `,
},
],
},
})
})
})
})
describe('a post that contains a poem', () => {
describe('query for more than one word, e.g. the title of the poem', () => {
it('finds the poem and another post that contains only one word but with lower score', async () => {
variables = { query: 'der panther' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Post',
id: 'd-post',
title: 'Der Panther',
content: `Sein Blick ist vom Vorübergehn der Stäbe<br>
so müd geworden, daß er nichts mehr hält.<br>
Ihm ist, als ob es tausend Stäbe gäbe<br>
und hinter tausend Stäben keine Welt.`,
},
{
__typename: 'Post',
id: 'g-post',
title: 'Zusammengesetzte Wörter',
content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`,
},
],
},
})
})
})
describe('query for the first four letters of two longer words', () => {
it('finds the posts that contain words starting with these four letters', async () => {
variables = { query: 'Vorü Subs' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: expect.arrayContaining([
{
__typename: 'Post',
id: 'd-post',
title: 'Der Panther',
content: `Sein Blick ist vom Vorübergehn der Stäbe<br>
so müd geworden, daß er nichts mehr hält.<br>
Ihm ist, als ob es tausend Stäbe gäbe<br>
und hinter tausend Stäben keine Welt.`,
},
{
__typename: 'Post',
id: 'g-post',
title: 'Zusammengesetzte Wörter',
content: `Ein Bindestrich kann zwischen zwei Substantiven auch dann gesetzt werden, wenn drei gleichlautende Buchstaben aufeinandertreffen. Das ist etwa bei einem „Teeei“ der Fall, das so korrekt geschrieben ist. Möglich ist hier auch die Schreibweise mit Bindestrich: Tee-Ei.`,
},
]),
},
})
})
})
})
})
describe('adding two users that have the same word in their slugs', () => {
beforeAll(async () => {
await Promise.all([
Factory.build('user', {
id: 'c-user',
name: 'Rainer Maria Rilke',
slug: 'rainer-maria-rilke',
}),
Factory.build('user', {
id: 'd-user',
name: 'Erich Maria Remarque',
slug: 'erich-maria-remarque',
}),
])
})
describe('query the word that both slugs contain', () => {
it('finds both users', async () => {
variables = { query: '-maria-' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: expect.arrayContaining([
{
__typename: 'User',
id: 'c-user',
name: 'Rainer Maria Rilke',
slug: 'rainer-maria-rilke',
},
{
__typename: 'User',
id: 'd-user',
name: 'Erich Maria Remarque',
slug: 'erich-maria-remarque',
},
]),
},
})
})
})
})
describe('adding a post, written by a user who is muted by the authenticated user', () => {
beforeAll(async () => {
const mutedUser = await Factory.build('user', {
id: 'muted-user',
name: 'Muted',
slug: 'muted',
})
await user.relateTo(mutedUser, 'muted')
await Factory.build(
'post',
{
id: 'muted-post',
title: 'Beleidigender Beitrag',
content: 'Dieser Beitrag stammt von einem bleidigendem Nutzer.',
},
{ authorId: 'muted-user' },
)
})
describe('query for text in a post written by a muted user', () => {
it('does not include the post of the muted user in the results', async () => {
variables = { query: 'beitrag' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: expect.not.arrayContaining([
{
__typename: 'Post',
id: 'muted-post',
title: 'Beleidigender Beitrag',
content: 'Dieser Beitrag stammt von einem bleidigendem Nutzer.',
},
]),
},
})
})
})
})
describe('adding a tag', () => {
beforeAll(async () => {
await Factory.build('tag', { id: 'myHashtag' })
})
describe('query the first four characters of the tag', () => {
it('finds the tag', async () => {
variables = { query: 'myha' }
await expect(query({ query: searchQuery, variables })).resolves.toMatchObject({
data: {
findResources: [
{
__typename: 'Tag',
id: 'myHashtag',
},
],
},
})
})
})
})
})
})
})

View File

@ -0,0 +1,47 @@
export function queryString(str) {
const normalizedString = normalizeWhitespace(str)
const escapedString = escapeSpecialCharacters(normalizedString)
return `
${matchWholeText(escapedString)}
${matchEachWordExactly(escapedString)}
${matchSomeWordsExactly(escapedString)}
${matchBeginningOfWords(escapedString)}
`
}
const matchWholeText = (str, boost = 8) => {
return `"${str}"^${boost}`
}
const matchEachWordExactly = (str, boost = 4) => {
if (!str.includes(' ')) return ''
const tmp = str
.split(' ')
.map((s, i) => (i === 0 ? `"${s}"` : `AND "${s}"`))
.join(' ')
return `(${tmp})^${boost}`
}
const matchSomeWordsExactly = (str, boost = 2) => {
if (!str.includes(' ')) return ''
return str
.split(' ')
.map((s) => `"${s}"^${boost}`)
.join(' ')
}
const matchBeginningOfWords = (str) => {
return str
.split(' ')
.filter((s) => s.length > 3)
.map((s) => s + '*')
.join(' ')
}
export function normalizeWhitespace(str) {
return str.replace(/\s+/g, ' ').trim()
}
export function escapeSpecialCharacters(str) {
return str.replace(/(["[\]&|\\{}+!()^~*?:/-])/g, '\\$1')
}

View File

@ -0,0 +1,43 @@
import { queryString, escapeSpecialCharacters, normalizeWhitespace } from './queryString'
describe('queryString', () => {
describe('special characters', () => {
it('does escaping correctly', () => {
expect(escapeSpecialCharacters('+ - && || ! ( ) { } [ ] ^ " ~ * ? : \\ / ')).toEqual(
'\\+ \\- \\&\\& \\|\\| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ \\/ ',
)
})
})
describe('whitespace', () => {
it('normalizes correctly', () => {
expect(normalizeWhitespace(' a \t \n b \n ')).toEqual('a b')
})
})
describe('exact match', () => {
it('boosts score by factor 8', () => {
expect(queryString('a couple of words')).toContain('"a couple of words"^8')
})
})
describe('match all words exactly', () => {
it('boosts score by factor 4', () => {
expect(queryString('a couple of words')).toContain(
'("a" AND "couple" AND "of" AND "words")^4',
)
})
})
describe('match at least one word exactly', () => {
it('boosts score by factor 2', () => {
expect(queryString('a couple of words')).toContain('"a"^2 "couple"^2 "of"^2 "words"^2')
})
})
describe('globbing for longer words', () => {
it('globs words with more than three characters', () => {
expect(queryString('a couple of words')).toContain('couple* words*')
})
})
})

View File

@ -7,7 +7,7 @@ export default {
const session = context.driver.session()
try {
const shoutWriteTxResultPromise = session.writeTransaction(async transaction => {
const shoutWriteTxResultPromise = session.writeTransaction(async (transaction) => {
const shoutTransactionResponse = await transaction.run(
`
MATCH (node {id: $id})<-[:WROTE]-(userWritten:User), (user:User {id: $userId})
@ -22,7 +22,7 @@ export default {
},
)
log(shoutTransactionResponse)
return shoutTransactionResponse.records.map(record => record.get('isShouted'))
return shoutTransactionResponse.records.map((record) => record.get('isShouted'))
})
const [isShouted] = await shoutWriteTxResultPromise
return isShouted
@ -35,7 +35,7 @@ export default {
const { id, type } = params
const session = context.driver.session()
try {
const unshoutWriteTxResultPromise = session.writeTransaction(async transaction => {
const unshoutWriteTxResultPromise = session.writeTransaction(async (transaction) => {
const unshoutTransactionResponse = await transaction.run(
`
MATCH (user:User {id: $userId})-[relation:SHOUTED]->(node {id: $id})
@ -50,7 +50,7 @@ export default {
},
)
log(unshoutTransactionResponse)
return unshoutTransactionResponse.records.map(record => record.get('isShouted'))
return unshoutTransactionResponse.records.map((record) => record.get('isShouted'))
})
const [isShouted] = await unshoutWriteTxResultPromise
return isShouted

View File

@ -132,7 +132,7 @@ describe('shout and unshout posts', () => {
},
)
const relationshipProperties = relation.records.map(
record => record.get('relationship').properties.createdAt,
(record) => record.get('relationship').properties.createdAt,
)
expect(relationshipProperties[0]).toEqual(expect.any(String))
})

View File

@ -15,7 +15,7 @@ export default {
countFollows: 'FOLLOWS',
countShouts: 'SHOUTED',
}
const statisticsReadTxResultPromise = session.readTransaction(async transaction => {
const statisticsReadTxResultPromise = session.readTransaction(async (transaction) => {
const statisticsTransactionResponse = await transaction.run(
`
CALL apoc.meta.stats() YIELD labels, relTypesCount
@ -23,7 +23,7 @@ export default {
`,
)
log(statisticsTransactionResponse)
return statisticsTransactionResponse.records.map(record => {
return statisticsTransactionResponse.records.map((record) => {
return {
...record.get('labels'),
...record.get('relTypesCount'),
@ -31,7 +31,7 @@ export default {
})
})
const [statistics] = await statisticsReadTxResultPromise
Object.keys(mapping).forEach(key => {
Object.keys(mapping).forEach((key) => {
const stat = statistics[mapping[key]]
counts[key] = stat ? stat.toNumber() : 0
})

View File

@ -16,7 +16,7 @@ export default {
const { user, driver } = context
if (!user) return null
const session = driver.session()
const currentUserTransactionPromise = session.readTransaction(async transaction => {
const currentUserTransactionPromise = session.readTransaction(async (transaction) => {
const result = await transaction.run(
`
MATCH (user:User {id: $id})
@ -26,7 +26,7 @@ export default {
{ id: user.id },
)
log(result)
return result.records.map(record => record.get('user'))
return result.records.map((record) => record.get('user'))
})
try {
const [currentUser] = await currentUserTransactionPromise
@ -44,16 +44,16 @@ export default {
email = normalizeEmail(email)
const session = driver.session()
try {
const loginReadTxResultPromise = session.readTransaction(async transaction => {
const loginReadTxResultPromise = session.readTransaction(async (transaction) => {
const loginTransactionResponse = await transaction.run(
`
MATCH (user:User {deleted: false})-[:PRIMARY_EMAIL]->(e:EmailAddress {email: $userEmail})
RETURN user {.id, .slug, .name, .avatar, .encryptedPassword, .role, .disabled, email:e.email} as user LIMIT 1
RETURN user {.id, .slug, .name, .encryptedPassword, .role, .disabled, email:e.email} as user LIMIT 1
`,
{ userEmail: email },
)
log(loginTransactionResponse)
return loginTransactionResponse.records.map(record => record.get('user'))
return loginTransactionResponse.records.map((record) => record.get('user'))
})
const [currentUser] = await loginReadTxResultPromise
if (

View File

@ -10,7 +10,7 @@ import { getNeode } from '../../db/neo4j'
const neode = getNeode()
let query, mutate, variables, req, user
const disable = async id => {
const disable = async (id) => {
const moderator = await Factory.build('user', { id: 'u2', role: 'moderator' })
const user = await neode.find('User', id)
const reportAgainstUser = await Factory.build('report')
@ -56,7 +56,7 @@ describe('isLoggedIn', () => {
isLoggedIn
}
`
const respondsWith = async expected => {
const respondsWith = async (expected) => {
await expect(query({ query: isLoggedInQuery })).resolves.toMatchObject(expected)
}
@ -106,14 +106,16 @@ describe('currentUser', () => {
id
slug
name
avatar
avatar {
url
}
email
role
}
}
`
const respondsWith = async expected => {
const respondsWith = async (expected) => {
await expect(query({ query: currentUserQuery, variables })).resolves.toMatchObject(expected)
}
@ -131,13 +133,15 @@ describe('currentUser', () => {
{
id: 'u3',
// the `id` is the only thing that has to match the decoded JWT bearer token
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg',
name: 'Matilde Hermiston',
slug: 'matilde-hermiston',
role: 'user',
},
{
email: 'test@example.org',
avatar: Factory.build('image', {
url: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg',
}),
},
)
const userBearerToken = encode({ id: 'u3' })
@ -149,7 +153,9 @@ describe('currentUser', () => {
data: {
currentUser: {
id: 'u3',
avatar: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg',
avatar: Factory.build('image', {
url: 'https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg',
}),
email: 'test@example.org',
name: 'Matilde Hermiston',
slug: 'matilde-hermiston',
@ -170,7 +176,7 @@ describe('login', () => {
}
`
const respondsWith = async expected => {
const respondsWith = async (expected) => {
await expect(mutate({ mutation: loginMutation, variables })).resolves.toMatchObject(expected)
}
@ -187,7 +193,7 @@ describe('login', () => {
describe('ask for a `token`', () => {
describe('with a valid email/password combination', () => {
it('responds with a JWT bearer token', async done => {
it('responds with a JWT bearer token', async (done) => {
const {
data: { login: token },
} = await mutate({ mutation: loginMutation, variables })
@ -286,7 +292,7 @@ describe('change password', () => {
}
`
const respondsWith = async expected => {
const respondsWith = async (expected) => {
await expect(mutate({ mutation: changePasswordMutation, variables })).resolves.toMatchObject(
expected,
)

View File

@ -1,14 +1,14 @@
import { neo4jgraphql } from 'neo4j-graphql-js'
import fileUpload from './fileUpload'
import { getNeode } from '../../db/neo4j'
import { UserInputError, ForbiddenError } from 'apollo-server'
import { mergeImage, deleteImage } from './images/images'
import Resolver from './helpers/Resolver'
import log from './helpers/databaseLogger'
import createOrUpdateLocations from './users/location'
const neode = getNeode()
export const getMutedUsers = async context => {
export const getMutedUsers = async (context) => {
const { neode } = context
const userModel = neode.model('User')
let mutedUsers = neode
@ -19,11 +19,11 @@ export const getMutedUsers = async context => {
.to('muted', userModel)
.return('muted')
mutedUsers = await mutedUsers.execute()
mutedUsers = mutedUsers.records.map(r => r.get('muted').properties)
mutedUsers = mutedUsers.records.map((r) => r.get('muted').properties)
return mutedUsers
}
export const getBlockedUsers = async context => {
export const getBlockedUsers = async (context) => {
const { neode } = context
const userModel = neode.model('User')
let blockedUsers = neode
@ -34,7 +34,7 @@ export const getBlockedUsers = async context => {
.to('blocked', userModel)
.return('blocked')
blockedUsers = await blockedUsers.execute()
blockedUsers = blockedUsers.records.map(r => r.get('blocked').properties)
blockedUsers = blockedUsers.records.map((r) => r.get('blocked').properties)
return blockedUsers
}
@ -60,7 +60,7 @@ export default {
let session
try {
session = context.driver.session()
const readTxResult = await session.readTransaction(txc => {
const readTxResult = await session.readTransaction((txc) => {
const result = txc.run(
`
MATCH (user:User)-[:PRIMARY_EMAIL]->(e:EmailAddress {email: $args.email})
@ -69,7 +69,7 @@ export default {
)
return result
})
return readTxResult.records.map(r => r.get('user').properties)
return readTxResult.records.map((r) => r.get('user').properties)
} finally {
session.close()
}
@ -140,6 +140,8 @@ export default {
},
UpdateUser: async (_parent, params, context, _resolveInfo) => {
const { termsAndConditionsAgreedVersion } = params
const { avatar: avatarInput } = params
delete params.avatar
if (termsAndConditionsAgreedVersion) {
const regEx = new RegExp(/^[0-9]+\.[0-9]+\.[0-9]+$/g)
if (!regEx.test(termsAndConditionsAgreedVersion)) {
@ -147,23 +149,26 @@ export default {
}
params.termsAndConditionsAgreedAt = new Date().toISOString()
}
params = await fileUpload(params, { file: 'avatarUpload', url: 'avatar' })
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const updateUserTransactionResponse = await transaction.run(
`
MATCH (user:User {id: $params.id})
SET user += $params
SET user.updatedAt = toString(datetime())
RETURN user
RETURN user {.*}
`,
{ params },
)
return updateUserTransactionResponse.records.map(record => record.get('user').properties)
const [user] = updateUserTransactionResponse.records.map((record) => record.get('user'))
if (avatarInput) {
await mergeImage(user, 'AVATAR_IMAGE', avatarInput, { transaction })
}
return user
})
try {
const [user] = await writeTxResultPromise
const user = await writeTxResultPromise
await createOrUpdateLocations(params.id, params.locationName, session)
return user
} catch (error) {
@ -173,52 +178,67 @@ export default {
}
},
DeleteUser: async (object, params, context, resolveInfo) => {
const { resource } = params
const { resource, id: userId } = params
const session = context.driver.session()
const { id: userId } = params
try {
const deleteUserTxResultPromise = session.writeTransaction(async (transaction) => {
if (resource && resource.length) {
await session.writeTransaction(transaction => {
resource.map(node => {
return transaction.run(
await Promise.all(
resource.map(async (node) => {
const txResult = await transaction.run(
`
MATCH (resource:${node})<-[:WROTE]-(author:User {id: $userId})
OPTIONAL MATCH (resource)<-[:COMMENTS]-(comment:Comment)
SET resource.deleted = true
SET resource.content = 'UNAVAILABLE'
SET resource.contentExcerpt = 'UNAVAILABLE'
SET comment.deleted = true
RETURN author
`,
MATCH (resource:${node})<-[:WROTE]-(author:User {id: $userId})
OPTIONAL MATCH (resource)<-[:COMMENTS]-(comment:Comment)
SET resource.deleted = true
SET resource.content = 'UNAVAILABLE'
SET resource.contentExcerpt = 'UNAVAILABLE'
SET resource.language = 'UNAVAILABLE'
SET resource.createdAt = 'UNAVAILABLE'
SET resource.updatedAt = 'UNAVAILABLE'
SET comment.deleted = true
RETURN resource {.*}
`,
{
userId,
},
)
})
})
return Promise.all(
txResult.records
.map((record) => record.get('resource'))
.map((resource) => deleteImage(resource, 'HERO_IMAGE', { transaction })),
)
}),
)
}
const deleteUserTxResultPromise = session.writeTransaction(async transaction => {
const deleteUserTransactionResponse = await transaction.run(
`
const deleteUserTransactionResponse = await transaction.run(
`
MATCH (user:User {id: $userId})
SET user.deleted = true
SET user.name = 'UNAVAILABLE'
SET user.about = 'UNAVAILABLE'
SET user.lastActiveAt = 'UNAVAILABLE'
SET user.createdAt = 'UNAVAILABLE'
SET user.updatedAt = 'UNAVAILABLE'
SET user.termsAndConditionsAgreedVersion = 'UNAVAILABLE'
SET user.encryptedPassword = null
WITH user
OPTIONAL MATCH (user)<-[:BELONGS_TO]-(email:EmailAddress)
DETACH DELETE email
WITH user
OPTIONAL MATCH (user)<-[:OWNED_BY]-(socialMedia:SocialMedia)
DETACH DELETE socialMedia
RETURN user
RETURN user {.*}
`,
{ userId },
)
log(deleteUserTransactionResponse)
return deleteUserTransactionResponse.records.map(record => record.get('user').properties)
})
const [user] = await deleteUserTxResultPromise
{ userId },
)
log(deleteUserTransactionResponse)
const [user] = deleteUserTransactionResponse.records.map((record) => record.get('user'))
await deleteImage(user, 'AVATAR_IMAGE', { transaction })
return user
})
try {
const user = await deleteUserTxResultPromise
return user
} finally {
session.close()
@ -231,14 +251,12 @@ export default {
const { id } = parent
const statement = `MATCH(u:User {id: {id}})-[:PRIMARY_EMAIL]->(e:EmailAddress) RETURN e`
const result = await neode.cypher(statement, { id })
const [{ email }] = result.records.map(r => r.get('e').properties)
const [{ email }] = result.records.map((r) => r.get('e').properties)
return email
},
...Resolver('User', {
undefinedToNull: [
'actorId',
'avatar',
'coverImg',
'deleted',
'disabled',
'locationName',
@ -272,6 +290,7 @@ export default {
badgesCount: '<-[:REWARDED]-(related:Badge)',
},
hasOne: {
avatar: '-[:AVATAR_IMAGE]->(related:Image)',
invitedBy: '<-[:INVITED]-(related:User)',
location: '-[:IS_IN]->(related:Location)',
},

View File

@ -29,7 +29,7 @@ beforeAll(() => {
mutate = createTestClient(server).mutate
})
afterEach(async () => {
beforeEach(async () => {
await cleanDatabase()
})
@ -495,6 +495,12 @@ describe('DeleteUser', () => {
mutate({ mutation: deleteUserMutation, variables }),
).resolves.toMatchObject(expectedResponse)
})
it('deletes user avatar and post hero images', async () => {
await expect(neode.all('Image')).resolves.toHaveLength(22)
await mutate({ mutation: deleteUserMutation, variables })
await expect(neode.all('Image')).resolves.toHaveLength(20)
})
})
})
@ -785,6 +791,12 @@ describe('DeleteUser', () => {
mutate({ mutation: deleteUserMutation, variables }),
).resolves.toMatchObject(expectedResponse)
})
it('deletes user avatar and post hero images', async () => {
await expect(neode.all('Image')).resolves.toHaveLength(22)
await mutate({ mutation: deleteUserMutation, variables })
await expect(neode.all('Image')).resolves.toHaveLength(20)
})
})
})
@ -834,7 +846,6 @@ describe('DeleteUser', () => {
).resolves.toMatchObject(expectedResponse)
})
})
describe('deletion of all post and comments requested', () => {
beforeEach(() => {
variables = { ...variables, resource: ['Post', 'Comment'] }
@ -882,27 +893,27 @@ describe('DeleteUser', () => {
})
})
})
})
})
describe('connected `EmailAddress` nodes', () => {
it('will be removed completely', async () => {
await expect(neode.all('EmailAddress')).resolves.toHaveLength(2)
await mutate({ mutation: deleteUserMutation, variables })
await expect(neode.all('EmailAddress')).resolves.toHaveLength(1)
})
})
describe('connected `EmailAddress` nodes', () => {
it('will be removed completely', async () => {
await expect(neode.all('EmailAddress')).resolves.toHaveLength(2)
await mutate({ mutation: deleteUserMutation, variables })
await expect(neode.all('EmailAddress')).resolves.toHaveLength(1)
})
})
describe('connected `SocialMedia` nodes', () => {
beforeEach(async () => {
const socialMedia = await Factory.build('socialMedia')
await socialMedia.relateTo(user, 'ownedBy')
})
describe('connected `SocialMedia` nodes', () => {
beforeEach(async () => {
const socialMedia = await Factory.build('socialMedia')
await socialMedia.relateTo(user, 'ownedBy')
})
it('will be removed completely', async () => {
await expect(neode.all('SocialMedia')).resolves.toHaveLength(1)
await mutate({ mutation: deleteUserMutation, variables })
await expect(neode.all('SocialMedia')).resolves.toHaveLength(0)
})
})
it('will be removed completely', async () => {
await expect(neode.all('SocialMedia')).resolves.toHaveLength(1)
await mutate({ mutation: deleteUserMutation, variables })
await expect(neode.all('SocialMedia')).resolves.toHaveLength(0)
})
})
})

View File

@ -7,9 +7,9 @@ import CONFIG from '../../../config'
const debug = Debug('human-connection:location')
const fetch = url => {
const fetch = (url) => {
return new Promise((resolve, reject) => {
request(url, function(error, response, body) {
request(url, function (error, response, body) {
if (error) {
reject(error)
} else {
@ -57,7 +57,7 @@ const createLocation = async (session, mapboxData) => {
}
mutation += ' RETURN l.id'
await session.writeTransaction(transaction => {
await session.writeTransaction((transaction) => {
return transaction.run(mutation, data)
})
}
@ -82,7 +82,7 @@ const createOrUpdateLocations = async (userId, locationName, session) => {
let data
res.features.forEach(item => {
res.features.forEach((item) => {
if (item.matching_place_name === locationName) {
data = item
}
@ -103,9 +103,9 @@ const createOrUpdateLocations = async (userId, locationName, session) => {
let parent = data
if (data.context) {
await asyncForEach(data.context, async ctx => {
await asyncForEach(data.context, async (ctx) => {
await createLocation(session, ctx)
await session.writeTransaction(transaction => {
await session.writeTransaction((transaction) => {
return transaction.run(
`
MATCH (parent:Location {id: $parentId}), (child:Location {id: $childId})
@ -122,7 +122,7 @@ const createOrUpdateLocations = async (userId, locationName, session) => {
})
}
// delete all current locations from user and add new location
await session.writeTransaction(transaction => {
await session.writeTransaction((transaction) => {
return transaction.run(
`
MATCH (user:User {id: $userId})-[relationship:IS_IN]->(location:Location)

View File

@ -8,28 +8,6 @@ const neode = getNeode()
const driver = getDriver()
let authenticatedUser, mutate, variables
const signupVerificationMutation = gql`
mutation(
$name: String!
$password: String!
$email: String!
$nonce: String!
$termsAndConditionsAgreedVersion: String!
$locationName: String
) {
SignupVerification(
name: $name
password: $password
email: $email
nonce: $nonce
termsAndConditionsAgreedVersion: $termsAndConditionsAgreedVersion
locationName: $locationName
) {
locationName
}
}
`
const updateUserMutation = gql`
mutation($id: ID!, $name: String!, $locationName: String) {
UpdateUser(id: $id, name: $name, locationName: $locationName) {
@ -38,51 +16,51 @@ const updateUserMutation = gql`
}
`
let newlyCreatedNodesWithLocales = [
const newlyCreatedNodesWithLocales = [
{
city: {
lat: 41.1534,
id: expect.stringContaining('place'),
type: 'place',
name: 'Hamburg',
nameEN: 'Hamburg',
nameDE: 'Hamburg',
namePT: 'Hamburg',
nameES: 'Hamburg',
nameFR: 'Hamburg',
nameIT: 'Hamburg',
nameEN: 'Hamburg',
type: 'place',
namePT: 'Hamburg',
nameRU: 'Хамбург',
nameDE: 'Hamburg',
nameNL: 'Hamburg',
name: 'Hamburg',
namePL: 'Hamburg',
id: 'place.5977106083398860',
lng: -74.5763,
lat: 41.1534,
},
state: {
namePT: 'Nova Jérsia',
nameRU: 'Нью-Джерси',
nameDE: 'New Jersey',
nameNL: 'New Jersey',
nameES: 'Nueva Jersey',
id: expect.stringContaining('region'),
type: 'region',
name: 'New Jersey',
namePL: 'New Jersey',
nameEN: 'New Jersey',
nameDE: 'New Jersey',
namePT: 'Nova Jérsia',
nameES: 'Nueva Jersey',
nameFR: 'New Jersey',
nameIT: 'New Jersey',
id: 'region.14919479731700330',
nameEN: 'New Jersey',
type: 'region',
nameRU: 'Нью-Джерси',
nameNL: 'New Jersey',
namePL: 'New Jersey',
},
country: {
namePT: 'Estados Unidos',
nameRU: 'Соединённые Штаты Америки',
nameDE: 'Vereinigte Staaten',
nameNL: 'Verenigde Staten van Amerika',
nameES: 'Estados Unidos',
namePL: 'Stany Zjednoczone',
id: expect.stringContaining('country'),
type: 'country',
name: 'United States of America',
nameEN: 'United States of America',
nameDE: 'Vereinigte Staaten',
namePT: 'Estados Unidos',
nameES: 'Estados Unidos',
nameFR: 'États-Unis',
nameIT: "Stati Uniti d'America",
id: 'country.9053006287256050',
nameEN: 'United States of America',
type: 'country',
nameRU: 'Соединённые Штаты Америки',
nameNL: 'Verenigde Staten van Amerika',
namePL: 'Stany Zjednoczone',
},
},
]
@ -105,82 +83,12 @@ beforeEach(() => {
authenticatedUser = null
})
afterEach(() => {
cleanDatabase()
})
afterEach(cleanDatabase)
describe('userMiddleware', () => {
describe('SignupVerification', () => {
beforeEach(async () => {
variables = {
...variables,
name: 'John Doe',
password: '123',
email: 'john@example.org',
nonce: '123456',
termsAndConditionsAgreedVersion: '0.1.0',
locationName: 'Hamburg, New Jersey, United States of America',
}
const args = {
email: 'john@example.org',
nonce: '123456',
}
await neode.model('EmailAddress').create(args)
})
it('creates a Location node with localised city/state/country names', async () => {
await mutate({ mutation: signupVerificationMutation, variables })
const locations = await neode.cypher(
`MATCH (city:Location)-[:IS_IN]->(state:Location)-[:IS_IN]->(country:Location) return city, state, country`,
)
expect(
locations.records.map(record => {
return {
city: record.get('city').properties,
state: record.get('state').properties,
country: record.get('country').properties,
}
}),
).toEqual(newlyCreatedNodesWithLocales)
})
})
describe('UpdateUser', () => {
let user
beforeEach(async () => {
newlyCreatedNodesWithLocales = [
{
city: {
lat: 53.55,
nameES: 'Hamburgo',
nameFR: 'Hambourg',
nameIT: 'Amburgo',
nameEN: 'Hamburg',
type: 'region',
namePT: 'Hamburgo',
nameRU: 'Гамбург',
nameDE: 'Hamburg',
nameNL: 'Hamburg',
namePL: 'Hamburg',
name: 'Hamburg',
id: 'region.10793468240398860',
lng: 10,
},
country: {
namePT: 'Alemanha',
nameRU: 'Германия',
nameDE: 'Deutschland',
nameNL: 'Duitsland',
nameES: 'Alemania',
name: 'Germany',
namePL: 'Niemcy',
nameFR: 'Allemagne',
nameIT: 'Germania',
id: 'country.10743216036480410',
nameEN: 'Germany',
type: 'country',
},
},
]
user = await Factory.build('user', {
id: 'updating-user',
})
@ -192,17 +100,18 @@ describe('userMiddleware', () => {
...variables,
id: 'updating-user',
name: 'Updating user',
locationName: 'Hamburg, Germany',
locationName: 'Hamburg, New Jersey, United States of America',
}
await mutate({ mutation: updateUserMutation, variables })
const locations = await neode.cypher(
`MATCH (city:Location)-[:IS_IN]->(country:Location) return city, country`,
`MATCH (city:Location)-[:IS_IN]->(state:Location)-[:IS_IN]->(country:Location) return city {.*}, state {.*}, country {.*}`,
)
expect(
locations.records.map(record => {
locations.records.map((record) => {
return {
city: record.get('city').properties,
country: record.get('country').properties,
city: record.get('city'),
state: record.get('state'),
country: record.get('country'),
}
}),
).toEqual(newlyCreatedNodesWithLocales)

View File

@ -90,7 +90,7 @@ describe('muteUser', () => {
beforeEach(() => {
currentUser = undefined
muteAction = variables => {
muteAction = (variables) => {
const { mutate } = createTestClient(server)
const muteUserMutation = gql`
mutation($id: ID!) {
@ -307,7 +307,7 @@ describe('unmuteUser', () => {
beforeEach(() => {
currentUser = undefined
unmuteAction = variables => {
unmuteAction = (variables) => {
const { mutate } = createTestClient(server)
const unmuteUserMutation = gql`
mutation($id: ID!) {

View File

@ -9,14 +9,10 @@ type Mutation {
SignupByInvitation(email: String!, token: String!): EmailAddress
SignupVerification(
nonce: String!
name: String!
email: String!
name: String!
password: String!
slug: String
avatar: String
coverImg: String
avatarUpload: Upload
locationName: String
about: String
termsAndConditionsAgreedVersion: String!
locale: String

View File

@ -0,0 +1,18 @@
type Image {
url: ID!,
# urlW34: String,
# urlW160: String,
# urlW320: String,
# urlW640: String,
# urlW1024: String,
alt: String,
sensitive: Boolean,
aspectRatio: Float,
}
input ImageInput {
alt: String,
upload: Upload,
sensitive: Boolean,
aspectRatio: Float,
}

View File

@ -40,7 +40,6 @@ input _PostFilter {
content_not_starts_with: String
content_ends_with: String
content_not_ends_with: String
image: String
visibility: Visibility
visibility_not: Visibility
visibility_in: [Visibility!]
@ -82,7 +81,6 @@ input _PostFilter {
emotions_none: _PostEMOTEDFilter
emotions_single: _PostEMOTEDFilter
emotions_every: _PostEMOTEDFilter
imageBlurred: Boolean
}
enum _PostOrdering {
@ -94,8 +92,6 @@ enum _PostOrdering {
slug_desc
content_asc
content_desc
image_asc
image_desc
visibility_asc
visibility_desc
createdAt_asc
@ -118,9 +114,7 @@ type Post {
slug: String!
content: String!
contentExcerpt: String
image: String
imageUpload: Upload
imageAspectRatio: Float
image: Image @relation(name: "HERO_IMAGE", direction: "OUT")
visibility: Visibility
deleted: Boolean
disabled: Boolean
@ -128,7 +122,6 @@ type Post {
createdAt: String
updatedAt: String
language: String
imageBlurred: Boolean
pinnedAt: String @cypher(
statement: "MATCH (this)<-[pinned:PINNED]-(:User) WHERE NOT this.deleted = true AND NOT this.disabled = true RETURN pinned.createdAt"
)
@ -178,14 +171,11 @@ type Mutation {
title: String!
slug: String
content: String!
image: String
imageUpload: Upload
image: ImageInput,
visibility: Visibility
language: String
categoryIds: [ID]
contentExcerpt: String
imageBlurred: Boolean
imageAspectRatio: Float
): Post
UpdatePost(
id: ID!
@ -193,13 +183,10 @@ type Mutation {
slug: String
content: String!
contentExcerpt: String
image: String
imageUpload: Upload
image: ImageInput,
visibility: Visibility
language: String
categoryIds: [ID]
imageBlurred: Boolean
imageAspectRatio: Float
): Post
DeletePost(id: ID!): Post
AddPostEmotions(to: _PostInput!, data: _EMOTEDInput!): EMOTED
@ -214,7 +201,6 @@ type Query {
title: String
slug: String
content: String
image: String
visibility: Visibility
pinned: Boolean
createdAt: String

View File

@ -1,4 +1,4 @@
union SearchResult = Post | User
union SearchResult = Post | User | Tag
type Query {
findResources(query: String!, limit: Int = 5): [SearchResult]!

Some files were not shown because too many files have changed in this diff Show More