Update prettier to v2

This commit is contained in:
roschaefer 2020-03-24 21:11:11 +01:00
parent af05492c04
commit 276ea79e8f
187 changed files with 548 additions and 594 deletions

View File

@ -129,7 +129,7 @@
"eslint-plugin-standard": "~4.0.1",
"jest": "~25.1.0",
"nodemon": "~2.0.2",
"prettier": "~1.19.1",
"prettier": "~2.0.2",
"rosie": "^2.0.1",
"supertest": "~4.0.2"
},

View File

@ -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

@ -36,7 +36,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.`)
}

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

@ -8,7 +8,7 @@ import CONFIG from '../config/index.js'
const neode = getNeode()
const uniqueImageUrl = imageUrl => {
const uniqueImageUrl = (imageUrl) => {
const newUrl = new URL(imageUrl, CONFIG.CLIENT_URI)
newUrl.search = `random=${uuid()}`
return newUrl.toString()
@ -18,7 +18,7 @@ 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)
@ -73,7 +73,7 @@ Factory.define('basicUser')
.attr('slug', ['slug', 'name'], (slug, name) => {
return slug || slugify(name, { lower: true })
})
.attr('encryptedPassword', ['password'], password => {
.attr('encryptedPassword', ['password'], (password) => {
return hashSync(password, 10)
})
@ -104,17 +104,17 @@ Factory.define('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')
})
@ -129,7 +129,7 @@ Factory.define('post')
imageBlurred: false,
imageAspectRatio: 1.333,
})
.attr('pinned', ['pinned'], pinned => {
.attr('pinned', ['pinned'], (pinned) => {
// Convert false to null
return pinned || null
})
@ -139,7 +139,7 @@ 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) => {
@ -152,8 +152,8 @@ Factory.define('post')
])
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) {
@ -165,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,14 +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"])',
'CALL db.index.fulltext.createNodeIndex("tag_fulltext_search",["Tag"],["id"])',
].map(statement => txc.run(statement)),
].map((statement) => txc.run(statement)),
)
})
try {
@ -34,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
@ -63,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

@ -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

@ -6,9 +6,9 @@ export const description = `
"Image" which contains metadata and image file urls.
`
const printSummaries = summaries => {
const printSummaries = (summaries) => {
console.log('=========================================')
summaries.forEach(stat => {
summaries.forEach((stat) => {
console.log(stat.query.text)
console.log(JSON.stringify(stat.counters, null, 2))
})
@ -18,7 +18,7 @@ const printSummaries = summaries => {
export async function up() {
const driver = getDriver()
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async txc => {
const writeTxResultPromise = session.writeTransaction(async (txc) => {
const runs = await Promise.all(
[
`
@ -48,7 +48,7 @@ export async function up() {
CREATE (user)-[:COVER_IMAGE]->(coverImage)
REMOVE user.coverImg
`,
].map(s => txc.run(s)),
].map((s) => txc.run(s)),
)
return runs.map(({ summary }) => summary)
})
@ -65,7 +65,7 @@ export async function up() {
export async function down() {
const driver = getDriver()
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async txc => {
const writeTxResultPromise = session.writeTransaction(async (txc) => {
const runs = await Promise.all(
[
`
@ -86,7 +86,7 @@ export async function down() {
SET user.coverImg = coverImage.url
DETACH DELETE coverImage
`,
].map(s => txc.run(s)),
].map((s) => txc.run(s)),
)
return runs.map(({ summary }) => summary)
})

View File

@ -20,7 +20,7 @@ export async function up(next) {
`)
try {
// Implement your migration here.
const users = await updateDeletedUserAttributes.records.map(record => record.get('user'))
const users = await updateDeletedUserAttributes.records.map((record) => record.get('user'))
// eslint-disable-next-line no-console
console.log(users)
await transaction.commit()

View File

@ -22,7 +22,7 @@ export async function up(next) {
`)
try {
// Implement your migration here.
const posts = await updateDeletedPostsAttributes.records.map(record => record.get('post'))
const posts = await updateDeletedPostsAttributes.records.map((record) => record.get('post'))
// eslint-disable-next-line no-console
console.log(posts)
await transaction.commit()

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()
@ -598,7 +598,7 @@ const languages = ['de', 'en', 'es', 'fr', 'it', 'pt', 'pl']
}),
])
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

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,7 +13,7 @@ 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 })
@ -23,7 +23,7 @@ export default async (driver, authorizationHeader) => {
`,
{ id },
)
return updateUserLastActiveTransactionResponse.records.map(record => record.get('user'))
return updateUserLastActiveTransactionResponse.records.map((record) => record.get('user'))
})
try {
const [currentUser] = await writeTxResultPromise

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

@ -6,7 +6,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 handleContentDataOfPost = async (resolve, root, args, context, resolveInfo) => {
@ -25,7 +25,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),
@ -37,7 +37,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 })
@ -46,7 +46,7 @@ const postAuthorOfComment = async (commentId, { context }) => {
{ commentId },
)
})
return postAuthorId.records.map(record => record.get('authorId'))
return postAuthorId.records.map((record) => record.get('authorId'))
} finally {
session.close()
}
@ -93,13 +93,13 @@ const notifyUsersOfMention = async (label, id, idsOfUsers, reason, context) => {
RETURN notification {.*, from: finalResource, to: properties(user)}
`
const session = context.driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const notificationTransactionResponse = await transaction.run(mentionedCypher, {
id,
idsOfUsers,
reason,
})
return notificationTransactionResponse.records.map(record => record.get('notification'))
return notificationTransactionResponse.records.map((record) => record.get('notification'))
})
try {
const notifications = await writeTxResultPromise
@ -115,7 +115,7 @@ const notifyUsersOfComment = async (label, commentId, postAuthorId, reason, cont
if (context.user.id === postAuthorId) return []
await validateNotifyUsers(label, reason)
const session = context.driver.session()
const writeTxResultPromise = await session.writeTransaction(async transaction => {
const writeTxResultPromise = await session.writeTransaction(async (transaction) => {
const notificationTransactionResponse = await transaction.run(
`
MATCH (postAuthor:User {id: $postAuthorId})-[:WROTE]->(post:Post)<-[:COMMENTS]-(comment:Comment { id: $commentId })<-[:WROTE]-(commenter:User)
@ -130,7 +130,7 @@ const notifyUsersOfComment = async (label, commentId, postAuthorId, reason, cont
`,
{ commentId, postAuthorId, reason },
)
return notificationTransactionResponse.records.map(record => record.get('notification'))
return notificationTransactionResponse.records.map((record) => record.get('notification'))
})
try {
const notifications = await writeTxResultPromise

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

@ -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

@ -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

@ -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

@ -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

@ -20,7 +20,7 @@ export async function deleteImage(resource, relationshipType, opts = {}) {
`,
{ resource },
)
const [image] = txResult.records.map(record => record.get('imageProps'))
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
@ -45,7 +45,7 @@ export async function mergeImage(resource, relationshipType, imageInput, opts =
`,
{ resource },
)
const [existingImage] = txResult.records.map(record => record.get('image'))
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)
@ -63,14 +63,14 @@ export async function mergeImage(resource, relationshipType, imageInput, opts =
`,
{ resource, image },
)
const [mergedImage] = txResult.records.map(record => record.get('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 => {
const result = await session.writeTransaction(async (transaction) => {
return wrappedCallback(...args, { ...opts, transaction })
})
return result
@ -98,7 +98,7 @@ const uploadImageFile = async (upload, uploadCallback = localFileUpload) => {
})
}
const sanitizeRelationshipType = relationshipType => {
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)) {
@ -115,7 +115,7 @@ const localFileUpload = ({ createReadStream, destination }) => {
)
}
const localFileDelete = async url => {
const localFileDelete = async (url) => {
const location = `public${url}`
if (existsSync(location)) unlinkSync(location)
}

View File

@ -50,13 +50,13 @@ describe('deleteImage', () => {
const session = driver.session()
let someString
try {
someString = await session.writeTransaction(async transaction => {
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'))
const [result] = txResult.records.map((record) => record.get('result'))
return result
})
} finally {
@ -66,11 +66,11 @@ describe('deleteImage', () => {
await expect(someString).toEqual('Hello')
})
it('rolls back the transaction in case of errors', async done => {
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 session.writeTransaction(async (transaction) => {
await deleteImage(user, 'AVATAR_IMAGE', {
deleteCallback,
transaction,
@ -203,7 +203,7 @@ describe('mergeImage', () => {
it('executes cypher statements within the transaction', async () => {
const session = driver.session()
try {
await session.writeTransaction(async transaction => {
await session.writeTransaction(async (transaction) => {
const image = await mergeImage(post, 'HERO_IMAGE', imageInput, {
uploadCallback,
deleteCallback,
@ -227,10 +227,10 @@ describe('mergeImage', () => {
})
})
it('rolls back the transaction in case of errors', async done => {
it('rolls back the transaction in case of errors', async (done) => {
const session = driver.session()
try {
await session.writeTransaction(async transaction => {
await session.writeTransaction(async (transaction) => {
const image = await mergeImage(post, 'HERO_IMAGE', imageInput, {
uploadCallback,
deleteCallback,

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

@ -42,7 +42,7 @@ export default {
const offset = args.offset && typeof args.offset === 'number' ? `SKIP ${args.offset}` : ''
const limit = args.first && typeof args.first === 'number' ? `LIMIT ${args.first}` : ''
const readTxResultPromise = session.readTransaction(async transaction => {
const readTxResultPromise = session.readTransaction(async (transaction) => {
const notificationsTransactionResponse = await transaction.run(
`
MATCH (resource {deleted: false, disabled: false})-[notification:NOTIFIED]->(user:User {id:$id})
@ -59,7 +59,7 @@ export default {
{ id: currentUser.id },
)
log(notificationsTransactionResponse)
return notificationsTransactionResponse.records.map(record => record.get('notification'))
return notificationsTransactionResponse.records.map((record) => record.get('notification'))
})
try {
const notifications = await readTxResultPromise
@ -73,7 +73,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})
@ -88,7 +88,7 @@ export default {
{ resourceId: args.id, id: currentUser.id },
)
log(markNotificationAsReadTransactionResponse)
return markNotificationAsReadTransactionResponse.records.map(record =>
return markNotificationAsReadTransactionResponse.records.map((record) =>
record.get('notification'),
)
})
@ -101,7 +101,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

@ -6,7 +6,7 @@ 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
@ -82,7 +82,7 @@ export default {
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)
@ -100,7 +100,7 @@ export default {
`,
{ userId: context.user.id, categoryIds, params },
)
const [post] = createPostTransactionResponse.records.map(record => record.get('post'))
const [post] = createPostTransactionResponse.records.map((record) => record.get('post'))
if (imageInput) {
await mergeImage(post, 'HERO_IMAGE', imageInput, { transaction })
}
@ -137,7 +137,7 @@ export default {
RETURN post, category
`
await session.writeTransaction(transaction => {
await session.writeTransaction((transaction) => {
return transaction.run(cypherDeletePreviousRelations, { params })
})
@ -152,12 +152,12 @@ export default {
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,
)
const [post] = updatePostTransactionResponse.records.map(record => record.get('post'))
const [post] = updatePostTransactionResponse.records.map((record) => record.get('post'))
await mergeImage(post, 'HERO_IMAGE', imageInput, { transaction })
return post
})
@ -170,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})
@ -184,7 +184,7 @@ export default {
`,
{ postId: args.id },
)
const [post] = deletePostTransactionResponse.records.map(record => record.get('post'))
const [post] = deletePostTransactionResponse.records.map((record) => record.get('post'))
await deleteImage(post, 'HERO_IMAGE', { transaction })
return post
})
@ -199,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})
@ -207,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 },
@ -226,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})
@ -235,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 },
@ -255,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)
@ -264,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'
@ -280,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'),
}))
@ -299,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})
@ -309,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
@ -351,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)
@ -362,7 +364,7 @@ export default {
{ id },
)
return relatedContributionsTransactionResponse.records.map(
record => record.get('post').properties,
(record) => record.get('post').properties,
)
})
try {

View File

@ -37,7 +37,7 @@ export default {
const { driver } = context
const session = driver.session()
const writeTxResultPromise = session.writeTransaction(async transaction => {
const writeTxResultPromise = session.writeTransaction(async (transaction) => {
const createUserTransactionResponse = await transaction.run(
`
MATCH(email:EmailAddress {nonce: $nonce, email: $email})
@ -57,7 +57,7 @@ export default {
`,
{ args, nonce, email },
)
const [user] = createUserTransactionResponse.records.map(record => record.get('user'))
const [user] = createUserTransactionResponse.records.map((record) => record.get('user'))
if (!user) throw new UserInputError('Invalid email or nonce')
return user
})

View File

@ -6,7 +6,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})
@ -29,7 +29,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
@ -81,7 +81,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)
`
@ -102,7 +102,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
@ -118,7 +118,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})
@ -127,14 +127,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,
@ -152,7 +152,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)
@ -162,14 +162,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

@ -54,7 +54,7 @@ export default {
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,
@ -81,7 +81,7 @@ export default {
log(postResults)
log(userResults)
log(tagResults)
return [...postResults.records, ...userResults.records, ...tagResults.records].map(r =>
return [...postResults.records, ...userResults.records, ...tagResults.records].map((r) =>
r.get('resource'),
)
} finally {

View File

@ -26,15 +26,15 @@ const matchSomeWordsExactly = (str, boost = 2) => {
if (!str.includes(' ')) return ''
return str
.split(' ')
.map(s => `"${s}"^${boost}`)
.map((s) => `"${s}"^${boost}`)
.join(' ')
}
const matchBeginningOfWords = str => {
const matchBeginningOfWords = (str) => {
return str
.split(' ')
.filter(s => s.length > 3)
.map(s => s + '*')
.filter((s) => s.length > 3)
.map((s) => s + '*')
.join(' ')
}

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,7 +44,7 @@ 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})
@ -53,7 +53,7 @@ export default {
{ 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)
}
@ -115,7 +115,7 @@ describe('currentUser', () => {
}
`
const respondsWith = async expected => {
const respondsWith = async (expected) => {
await expect(query({ query: currentUserQuery, variables })).resolves.toMatchObject(expected)
}
@ -176,7 +176,7 @@ describe('login', () => {
}
`
const respondsWith = async expected => {
const respondsWith = async (expected) => {
await expect(mutate({ mutation: loginMutation, variables })).resolves.toMatchObject(expected)
}
@ -193,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 })
@ -292,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

@ -8,7 +8,7 @@ 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()
}
@ -151,7 +151,7 @@ export default {
}
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})
@ -161,7 +161,7 @@ export default {
`,
{ params },
)
const [user] = updateUserTransactionResponse.records.map(record => record.get('user'))
const [user] = updateUserTransactionResponse.records.map((record) => record.get('user'))
if (avatarInput) {
await mergeImage(user, 'AVATAR_IMAGE', avatarInput, { transaction })
}
@ -181,10 +181,10 @@ export default {
const { resource, id: userId } = params
const session = context.driver.session()
const deleteUserTxResultPromise = session.writeTransaction(async transaction => {
const deleteUserTxResultPromise = session.writeTransaction(async (transaction) => {
if (resource && resource.length) {
await Promise.all(
resource.map(async node => {
resource.map(async (node) => {
const txResult = await transaction.run(
`
MATCH (resource:${node})<-[:WROTE]-(author:User {id: $userId})
@ -204,8 +204,8 @@ export default {
)
return Promise.all(
txResult.records
.map(record => record.get('resource'))
.map(resource => deleteImage(resource, 'HERO_IMAGE', { transaction })),
.map((record) => record.get('resource'))
.map((resource) => deleteImage(resource, 'HERO_IMAGE', { transaction })),
)
}),
)
@ -233,7 +233,7 @@ export default {
{ userId },
)
log(deleteUserTransactionResponse)
const [user] = deleteUserTransactionResponse.records.map(record => record.get('user'))
const [user] = deleteUserTransactionResponse.records.map((record) => record.get('user'))
await deleteImage(user, 'AVATAR_IMAGE', { transaction })
return user
})
@ -251,7 +251,7 @@ 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', {

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

@ -107,7 +107,7 @@ describe('userMiddleware', () => {
`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'),
state: record.get('state'),

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

@ -20,7 +20,7 @@ const options = {
host: REDIS_DOMAIN,
port: REDIS_PORT,
password: REDIS_PASSWORD,
retryStrategy: times => {
retryStrategy: (times) => {
return Math.min(times * 50, 2000)
},
}
@ -36,7 +36,7 @@ export const pubsub = prodPubsub || devPubsub
const driver = getDriver()
const neode = getNeode()
const getContext = async req => {
const getContext = async (req) => {
const user = await decode(driver, req.headers.authorization)
return {
driver,
@ -48,7 +48,7 @@ const getContext = async req => {
},
}
}
export const context = async options => {
export const context = async (options) => {
const { connection, req } = options
if (connection) {
return connection.context
@ -57,7 +57,7 @@ export const context = async options => {
}
}
const createServer = options => {
const createServer = (options) => {
const defaults = {
context,
schema: middleware(schema),
@ -68,9 +68,9 @@ const createServer = options => {
},
debug: !!CONFIG.DEBUG,
tracing: !!CONFIG.DEBUG,
formatError: error => {
formatError: (error) => {
if (error.message === 'ERROR_VALIDATION') {
return new Error(error.originalError.details.map(d => d.message))
return new Error(error.originalError.details.map((d) => d.message))
}
return error
},

View File

@ -7313,10 +7313,10 @@ prettier-linter-helpers@^1.0.0:
dependencies:
fast-diff "^1.1.2"
prettier@~1.19.1:
version "1.19.1"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.19.1.tgz#f7d7f5ff8a9cd872a7be4ca142095956a60797cb"
integrity sha512-s7PoyDv/II1ObgQunCbB9PdLmUcBZcnWOcxDh7O0N/UwDEsHyqkW+Qh28jW+mVuCdx7gLB0BotYI1Y6uI9iyew==
prettier@~2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.0.2.tgz#1ba8f3eb92231e769b7fcd7cb73ae1b6b74ade08"
integrity sha512-5xJQIPT8BraI7ZnaDwSbu5zLrB6vvi8hVV58yHQ+QK64qrY40dULy0HSRlQ2/2IdzeBpjhDkqdcFBnFeDEMVdg==
pretty-format@^25.1.0:
version "25.1.0"

View File

@ -1,4 +1,4 @@
export default function(to, from, savedPosition) {
export default function (to, from, savedPosition) {
if (savedPosition) return savedPosition
// Edge case: If you click on a notification from a comment and then on the

View File

@ -2,7 +2,7 @@ const svgFileList = require.context('./svgs', true, /\.svg/)
const icons = {}
const iconNames = []
svgFileList.keys().forEach(fileName => {
svgFileList.keys().forEach((fileName) => {
const svgCode = svgFileList(fileName)
const iconName = fileName.replace('./', '').replace('.svg', '')
icons[iconName] = svgCode

View File

@ -21,7 +21,7 @@ describe('AvatarMenu.vue', () => {
return { href: '/profile/u343/matt' }
}),
},
$t: jest.fn(a => a),
$t: jest.fn((a) => a),
}
getters = {
'auth/user': () => {
@ -86,21 +86,21 @@ describe('AvatarMenu.vue', () => {
it('displays a link to user profile', () => {
const profileLink = wrapper
.findAll('.ds-menu-item span')
.at(wrapper.vm.routes.findIndex(route => route.path === '/profile/u343/matt'))
.at(wrapper.vm.routes.findIndex((route) => route.path === '/profile/u343/matt'))
expect(profileLink.exists()).toBe(true)
})
it('displays a link to the notifications page', () => {
const notificationsLink = wrapper
.findAll('.ds-menu-item span')
.at(wrapper.vm.routes.findIndex(route => route.path === '/notifications'))
.at(wrapper.vm.routes.findIndex((route) => route.path === '/notifications'))
expect(notificationsLink.exists()).toBe(true)
})
it('displays a link to the settings page', () => {
const settingsLink = wrapper
.findAll('.ds-menu-item span')
.at(wrapper.vm.routes.findIndex(route => route.path === '/settings'))
.at(wrapper.vm.routes.findIndex((route) => route.path === '/settings'))
expect(settingsLink.exists()).toBe(true)
})
})
@ -121,7 +121,7 @@ describe('AvatarMenu.vue', () => {
it('displays a link to moderation page', () => {
const moderationLink = wrapper
.findAll('.ds-menu-item span')
.at(wrapper.vm.routes.findIndex(route => route.path === '/moderation'))
.at(wrapper.vm.routes.findIndex((route) => route.path === '/moderation'))
expect(moderationLink.exists()).toBe(true)
})
@ -147,7 +147,7 @@ describe('AvatarMenu.vue', () => {
it('displays a link to admin page', () => {
const adminLink = wrapper
.findAll('.ds-menu-item span')
.at(wrapper.vm.routes.findIndex(route => route.path === '/admin'))
.at(wrapper.vm.routes.findIndex((route) => route.path === '/admin'))
expect(adminLink.exists()).toBe(true)
})

View File

@ -20,7 +20,7 @@
{{ $t('login.hello') }}
<b>{{ userName }}</b>
<template v-if="user.role !== 'user'">
<ds-text color="softer" size="small" style="margin-bottom: 0">
<ds-text color="softer" size="small" style="margin-bottom: 0;">
{{ user.role | camelCase }}
</ds-text>
</template>

View File

@ -29,8 +29,8 @@ describe('CommentCard.vue', () => {
locale: () => 'en',
},
$filters: {
truncate: a => a,
removeHtml: a => a,
truncate: (a) => a,
removeHtml: (a) => a,
},
$route: { hash: '' },
$scrollTo: jest.fn(),

View File

@ -25,7 +25,7 @@ describe('CommentForm.vue', () => {
success: jest.fn(),
},
$filters: {
removeHtml: a => a,
removeHtml: (a) => a,
},
}
})

View File

@ -104,7 +104,7 @@ export default {
this.disabled = true
this.$apollo
.mutate(mutateParams)
.then(res => {
.then((res) => {
this.loading = false
if (!this.update) {
const {
@ -125,7 +125,7 @@ export default {
this.closeEditWindow()
}
})
.catch(err => {
.catch((err) => {
this.$toast.error(err.message)
})
},

View File

@ -6,7 +6,7 @@ import Vue from 'vue'
const localVue = global.localVue
localVue.filter('truncate', string => string)
localVue.filter('truncate', (string) => string)
localVue.directive('scrollTo', jest.fn())
config.stubs['v-popover'] = '<span><slot /></span>'
@ -42,8 +42,8 @@ describe('CommentList.vue', () => {
mocks = {
$t: jest.fn(),
$filters: {
truncate: a => a,
removeHtml: a => a,
truncate: (a) => a,
removeHtml: (a) => a,
},
$scrollTo: jest.fn(),
$route: { hash: '' },

View File

@ -6,7 +6,7 @@ import faker from 'faker'
helpers.init()
const commentMock = fields => {
const commentMock = (fields) => {
return {
id: faker.random.uuid(),
title: faker.lorem.sentence(),

View File

@ -48,7 +48,7 @@ export default {
return anchor === '#comments'
},
updateCommentList(updatedComment) {
this.postComments = this.postComments.map(comment => {
this.postComments = this.postComments.map((comment) => {
return comment.id === updatedComment.id ? updatedComment : comment
})
},

View File

@ -17,7 +17,7 @@ let getters, mutations, mocks, menuToggle, openModalSpy
describe('ContentMenu.vue', () => {
beforeEach(() => {
mocks = {
$t: jest.fn(str => str),
$t: jest.fn((str) => str),
$i18n: {
locale: () => 'en',
},
@ -68,7 +68,7 @@ describe('ContentMenu.vue', () => {
expect(
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'post.menu.edit')
.filter((item) => item.text() === 'post.menu.edit')
.at(0)
.find('span.ds-menu-item-link')
.attributes('to'),
@ -78,7 +78,7 @@ describe('ContentMenu.vue', () => {
it('can delete the contribution', () => {
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'post.menu.delete')
.filter((item) => item.text() === 'post.menu.delete')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('confirm', 'delete')
@ -98,7 +98,7 @@ describe('ContentMenu.vue', () => {
})
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'post.menu.pin')
.filter((item) => item.text() === 'post.menu.pin')
.at(0)
.trigger('click')
expect(wrapper.emitted('pinPost')).toEqual([
@ -122,7 +122,7 @@ describe('ContentMenu.vue', () => {
})
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'post.menu.unpin')
.filter((item) => item.text() === 'post.menu.unpin')
.at(0)
.trigger('click')
expect(wrapper.emitted('unpinPost')).toEqual([
@ -151,7 +151,7 @@ describe('ContentMenu.vue', () => {
it('edit the comment', () => {
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'comment.menu.edit')
.filter((item) => item.text() === 'comment.menu.edit')
.at(0)
.trigger('click')
expect(wrapper.emitted('editComment')).toBeTruthy()
@ -159,7 +159,7 @@ describe('ContentMenu.vue', () => {
it('delete the comment', () => {
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'comment.menu.delete')
.filter((item) => item.text() === 'comment.menu.delete')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('confirm', 'delete')
@ -180,7 +180,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'report.contribution.title')
.filter((item) => item.text() === 'report.contribution.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('report')
@ -197,7 +197,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'report.comment.title')
.filter((item) => item.text() === 'report.comment.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('report')
@ -214,7 +214,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'report.user.title')
.filter((item) => item.text() === 'report.user.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('report')
@ -231,7 +231,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'report.organization.title')
.filter((item) => item.text() === 'report.organization.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('report')
@ -253,7 +253,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'disable.contribution.title')
.filter((item) => item.text() === 'disable.contribution.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('disable')
@ -271,7 +271,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'disable.comment.title')
.filter((item) => item.text() === 'disable.comment.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('disable')
@ -289,7 +289,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'disable.user.title')
.filter((item) => item.text() === 'disable.user.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('disable')
@ -307,7 +307,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'disable.organization.title')
.filter((item) => item.text() === 'disable.organization.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('disable')
@ -325,7 +325,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'release.contribution.title')
.filter((item) => item.text() === 'release.contribution.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('release')
@ -343,7 +343,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'release.comment.title')
.filter((item) => item.text() === 'release.comment.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('release')
@ -361,7 +361,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'release.user.title')
.filter((item) => item.text() === 'release.user.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('release')
@ -379,7 +379,7 @@ describe('ContentMenu.vue', () => {
openModalSpy = jest.spyOn(wrapper.vm, 'openModal')
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'release.organization.title')
.filter((item) => item.text() === 'release.organization.title')
.at(0)
.trigger('click')
expect(openModalSpy).toHaveBeenCalledWith('release')
@ -400,7 +400,7 @@ describe('ContentMenu.vue', () => {
expect(
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'settings.name')
.filter((item) => item.text() === 'settings.name')
.at(0)
.find('span.ds-menu-item-link')
.attributes('to'),
@ -418,7 +418,7 @@ describe('ContentMenu.vue', () => {
})
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'settings.muted-users.mute')
.filter((item) => item.text() === 'settings.muted-users.mute')
.at(0)
.trigger('click')
expect(wrapper.emitted('mute')).toEqual([
@ -442,7 +442,7 @@ describe('ContentMenu.vue', () => {
})
wrapper
.findAll('.ds-menu-item')
.filter(item => item.text() === 'settings.muted-users.unmute')
.filter((item) => item.text() === 'settings.muted-users.unmute')
.at(0)
.trigger('click')
expect(wrapper.emitted('unmute')).toEqual([

View File

@ -46,7 +46,7 @@ export default {
resourceType: {
type: String,
required: true,
validator: value => {
validator: (value) => {
return value.match(/(contribution|comment|organization|user)/)
},
},

View File

@ -140,7 +140,9 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
englishLanguage = wrapper.findAll('li').filter(language => language.text() === 'English')
englishLanguage = wrapper
.findAll('li')
.filter((language) => language.text() === 'English')
englishLanguage.trigger('click')
dataPrivacyButton = await wrapper
.find(CategoriesSelect)
@ -206,7 +208,9 @@ describe('ContributionForm.vue', () => {
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
wrapper.find(CategoriesSelect).setData({ categories })
englishLanguage = wrapper.findAll('li').filter(language => language.text() === 'English')
englishLanguage = wrapper
.findAll('li')
.filter((language) => language.text() === 'English')
englishLanguage.trigger('click')
await Vue.nextTick()
dataPrivacyButton = await wrapper
@ -223,7 +227,9 @@ describe('ContributionForm.vue', () => {
it('supports changing the language', async () => {
expectedParams.variables.language = 'de'
deutschLanguage = wrapper.findAll('li').filter(language => language.text() === 'Deutsch')
deutschLanguage = wrapper
.findAll('li')
.filter((language) => language.text() === 'Deutsch')
deutschLanguage.trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
@ -237,7 +243,7 @@ describe('ContributionForm.vue', () => {
}
const spy = jest
.spyOn(FileReader.prototype, 'readAsDataURL')
.mockImplementation(function() {
.mockImplementation(function () {
this.onload({ target: { result: 'someUrlToImage' } })
})
wrapper.find(ImageUploader).vm.$emit('addHeroImage', imageUpload)
@ -288,7 +294,9 @@ describe('ContributionForm.vue', () => {
await wrapper.vm.updateEditorContent(postContent)
categoryIds = ['cat12']
wrapper.find(CategoriesSelect).setData({ categories })
englishLanguage = wrapper.findAll('li').filter(language => language.text() === 'English')
englishLanguage = wrapper
.findAll('li')
.filter((language) => language.text() === 'English')
englishLanguage.trigger('click')
await Vue.nextTick()
dataPrivacyButton = await wrapper

View File

@ -108,7 +108,7 @@ export default {
data() {
const { title, content, image, language, categories } = this.contribution
const languageOptions = orderBy(locales, 'name').map(locale => {
const languageOptions = orderBy(locales, 'name').map((locale) => {
return { label: locale.name, value: locale.code }
})
const { sensitive: imageBlurred = false, aspectRatio: imageAspectRatio = null } = image || {}
@ -120,8 +120,8 @@ export default {
image: image || null,
imageAspectRatio,
imageBlurred,
language: languageOptions.find(option => option.value === language) || null,
categoryIds: categories ? categories.map(category => category.id) : [],
language: languageOptions.find((option) => option.value === language) || null,
categoryIds: categories ? categories.map((category) => category.id) : [],
},
formSchema: {
title: { required: true, min: 3, max: 100 },
@ -190,7 +190,7 @@ export default {
params: { id: result.id, slug: result.slug },
})
})
.catch(err => {
.catch((err) => {
this.$toast.error(err.message)
this.loading = false
})

View File

@ -90,7 +90,7 @@ export default {
this.logout()
this.$router.history.push('/')
})
.catch(error => {
.catch((error) => {
this.$toast.error(error.message)
})
},

View File

@ -12,7 +12,7 @@ describe('DonationInfo.vue', () => {
beforeEach(() => {
mocks = {
$t: jest.fn(string => string),
$t: jest.fn((string) => string),
$i18n: {
locale: () => 'de',
},
@ -22,19 +22,11 @@ describe('DonationInfo.vue', () => {
const Wrapper = () => mount(DonationInfo, { mocks, localVue })
it('includes a link to the Human Connection donations website', () => {
expect(
Wrapper()
.find('a')
.attributes('href'),
).toBe('https://human-connection.org/spenden/')
expect(Wrapper().find('a').attributes('href')).toBe('https://human-connection.org/spenden/')
})
it('displays a call to action button', () => {
expect(
Wrapper()
.find('.base-button')
.text(),
).toBe('donations.donate-now')
expect(Wrapper().find('.base-button').text()).toBe('donations.donate-now')
})
it.skip('creates a title from the current month and a translation string', () => {

View File

@ -48,8 +48,9 @@ export default {
if (isOpen) {
this.$nextTick(() => {
setTimeout(() => {
const paddingRightStyle = `${window.innerWidth -
document.documentElement.clientWidth}px`
const paddingRightStyle = `${
window.innerWidth - document.documentElement.clientWidth
}px`
const navigationElement = document.querySelector('.main-navigation')
document.body.style.paddingRight = paddingRightStyle
document.body.classList.add('dropdown-open')

View File

@ -10,7 +10,7 @@ describe('DropdownFilter.vue', () => {
beforeEach(() => {
propsData = {}
mocks = {
$t: jest.fn(a => a),
$t: jest.fn((a) => a),
}
})
@ -43,7 +43,7 @@ describe('DropdownFilter.vue', () => {
wrapper.find('.dropdown-filter').trigger('click')
allLink = wrapper
.findAll('.dropdown-menu-item')
.at(propsData.filterOptions.findIndex(option => option.label === 'All'))
.at(propsData.filterOptions.findIndex((option) => option.label === 'All'))
})
it('displays a link for All', () => {
@ -53,21 +53,21 @@ describe('DropdownFilter.vue', () => {
it('displays a link for Read', () => {
const readLink = wrapper
.findAll('.dropdown-menu-item')
.at(propsData.filterOptions.findIndex(option => option.label === 'Read'))
.at(propsData.filterOptions.findIndex((option) => option.label === 'Read'))
expect(readLink.text()).toEqual('Read')
})
it('displays a link for Unread', () => {
const unreadLink = wrapper
.findAll('.dropdown-menu-item')
.at(propsData.filterOptions.findIndex(option => option.label === 'Unread'))
.at(propsData.filterOptions.findIndex((option) => option.label === 'Unread'))
expect(unreadLink.text()).toEqual('Unread')
})
it('clicking on menu item emits filter', () => {
allLink.trigger('click')
expect(wrapper.emitted().filter[0]).toEqual(
propsData.filterOptions.filter(option => option.label === 'All'),
propsData.filterOptions.filter((option) => option.label === 'All'),
)
})
})

View File

@ -35,7 +35,7 @@ const users = [
storiesOf('Editor', module)
.addDecorator(withA11y)
.addDecorator(storyFn => {
.addDecorator((storyFn) => {
const ctx = storyFn()
return {
components: { ctx },

View File

@ -80,7 +80,7 @@ export default {
items: () => {
return this.users
},
onEnter: props => this.openSuggestionList(props, MENTION),
onEnter: (props) => this.openSuggestionList(props, MENTION),
onChange: this.updateSuggestionList,
onExit: this.closeSuggestionList,
onKeyDown: this.navigateSuggestionList,
@ -95,7 +95,7 @@ export default {
items: () => {
return this.hashtags
},
onEnter: props => this.openSuggestionList(props, HASHTAG),
onEnter: (props) => this.openSuggestionList(props, HASHTAG),
onChange: this.updateSuggestionList,
onExit: this.closeSuggestionList,
onKeyDown: this.navigateSuggestionList,
@ -109,7 +109,7 @@ export default {
watch: {
placeholder: {
immediate: true,
handler: function(val) {
handler: function (val) {
if (!val || !this.editor) {
return
}
@ -129,7 +129,7 @@ export default {
new EventHandler(),
new History(),
],
onUpdate: e => {
onUpdate: (e) => {
clearTimeout(throttleInputEvent)
throttleInputEvent = setTimeout(() => this.onUpdate(e), 300)
},
@ -197,7 +197,7 @@ export default {
return items.slice(0, 15)
}
const filteredList = items.filter(item => {
const filteredList = items.filter((item) => {
const itemString = item.slug || item.id
return itemString.toLowerCase().includes(query.toLowerCase())
})

View File

@ -14,7 +14,7 @@
<menu-bar-button
ref="linkButton"
:isActive="isActive.link()"
:onClick="event => toggleLinkInput(getMarkAttrs('link'), event.currentTarget)"
:onClick="(event) => toggleLinkInput(getMarkAttrs('link'), event.currentTarget)"
icon="link"
/>

View File

@ -11,7 +11,7 @@
</li>
<template v-if="isHashtag">
<li v-if="!query" class="suggestion-list__item hint">{{ $t('editor.hashtag.addLetter') }}</li>
<template v-else-if="!filteredItems.find(el => el.id === query)">
<template v-else-if="!filteredItems.find((el) => el.id === query)">
<li class="suggestion-list__item hint">{{ $t('editor.hashtag.addHashtag') }}</li>
<li class="suggestion-list__item" @click="selectItem({ id: query })">
#{{ query | truncate(50) }}

View File

@ -1,11 +1,11 @@
import { Plugin } from 'prosemirror-state'
import { Slice, Fragment } from 'prosemirror-model'
export default function(regexp, type, getAttrs) {
const handler = fragment => {
export default function (regexp, type, getAttrs) {
const handler = (fragment) => {
const nodes = []
fragment.forEach(child => {
fragment.forEach((child) => {
if (child.isText) {
const { text } = child
let pos = 0
@ -43,7 +43,7 @@ export default function(regexp, type, getAttrs) {
return new Plugin({
props: {
transformPasted: slice => new Slice(handler(slice.content), slice.openStart, slice.openEnd),
transformPasted: (slice) => new Slice(handler(slice.content), slice.openStart, slice.openEnd),
},
})
}

View File

@ -26,7 +26,7 @@ export default class Embed extends Node {
// source: https://stackoverflow.com/a/3809435
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/g,
type,
url => ({ dataEmbedUrl: url }),
(url) => ({ dataEmbedUrl: url }),
),
]
}
@ -43,12 +43,12 @@ export default class Embed extends Node {
parseDOM: [
{
tag: 'a[href].embed',
getAttrs: dom => ({
getAttrs: (dom) => ({
dataEmbedUrl: dom.getAttribute('href'),
}),
},
],
toDOM: node => [
toDOM: (node) => [
'a',
{
href: node.attrs.dataEmbedUrl,

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