Merge pull request #2163 from Human-Connection/2119_Create_Post_consistent_form_input_validation-improvements

2119 create post consistent form input validation improvements
This commit is contained in:
mattwr18 2019-11-18 15:04:09 +01:00 committed by GitHub
commit 0ca20187dc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 250 additions and 257 deletions

View File

@ -5,9 +5,12 @@ import {
} from "cypress-cucumber-preprocessor/steps";
import helpers from "../../support/helpers";
import { VERSION } from '../../constants/terms-and-conditions-version.js'
import locales from '../../../webapp/locales'
import orderBy from 'lodash/orderBy'
/* global cy */
const languages = orderBy(locales, 'name')
let lastPost = {};
let loginCredentials = {
@ -245,6 +248,12 @@ Then("I select a category", () => {
.click();
});
When("I choose {string} as the language for the post", (languageCode) => {
cy.get('.ds-flex-item > .ds-form-item .ds-select ')
.click().get('.ds-select-option')
.eq(languages.findIndex(l => l.code === languageCode)).click()
})
Then("the post shows up on the landing page at position {int}", index => {
cy.openPage("landing");
const selector = `.post-card:nth-child(${index}) > .ds-card-content`;
@ -536,4 +545,4 @@ Then("I see only one post with the title {string}", title => {
.find(".post-link")
.should("have.length", 1);
cy.get(".main-container").contains(".post-link", title);
});
});

View File

@ -20,6 +20,7 @@ Feature: Notification for a mention
"""
And mention "@matt-rider" in the text
And I select a category
And I choose "en" as the language for the post
And I click on "Save"
When I log out
And I log in with the following credentials:

View File

@ -17,7 +17,8 @@ Feature: Create a post
Human Connection is a free and open-source social network
for active citizenship.
"""
Then I select a category
And I select a category
And I choose "en" as the language for the post
And I click on "Save"
Then I get redirected to ".../my-first-post"
And the post was saved successfully

View File

@ -8,10 +8,12 @@ localVue.use(Styleguide)
describe('CategoriesSelect.vue', () => {
let wrapper
let mocks
let provide
let democracyAndPolitics
let environmentAndNature
let consumptionAndSustainablity
const propsData = { model: 'categoryIds' }
const categories = [
{
id: 'cat9',
@ -35,6 +37,11 @@ describe('CategoriesSelect.vue', () => {
},
]
beforeEach(() => {
provide = {
$parentForm: {
update: jest.fn(),
},
}
mocks = {
$t: jest.fn(),
}
@ -42,7 +49,7 @@ describe('CategoriesSelect.vue', () => {
describe('shallowMount', () => {
const Wrapper = () => {
return mount(CategoriesSelect, { mocks, localVue })
return mount(CategoriesSelect, { propsData, mocks, localVue, provide })
}
beforeEach(() => {
@ -60,8 +67,8 @@ describe('CategoriesSelect.vue', () => {
expect(wrapper.vm.selectedCategoryIds).toEqual([categories[0].id])
})
it('emits an updateCategories event when the selectedCategoryIds changes', () => {
expect(wrapper.emitted().updateCategories[0][0]).toEqual([categories[0].id])
it('calls $parent.update with selected category ids', () => {
expect(provide.$parentForm.update).toHaveBeenCalledWith('categoryIds', ['cat9'])
})
it('removes categories when clicked a second time', () => {

View File

@ -28,16 +28,23 @@
<script>
import CategoryQuery from '~/graphql/CategoryQuery'
import xor from 'lodash/xor'
export default {
inject: {
$parentForm: {
default: null,
},
},
props: {
existingCategoryIds: { type: Array, default: () => [] },
model: { type: String, required: true },
},
data() {
return {
categories: null,
selectedMax: 3,
selectedCategoryIds: [],
selectedCategoryIds: this.existingCategoryIds,
}
},
computed: {
@ -48,35 +55,15 @@ export default {
return this.selectedCount >= this.selectedMax
},
},
watch: {
selectedCategoryIds(categoryIds) {
this.$emit('updateCategories', categoryIds)
},
existingCategoryIds: {
immediate: true,
handler: function(existingCategoryIds) {
if (!existingCategoryIds || !existingCategoryIds.length) {
return
}
this.selectedCategoryIds = existingCategoryIds
},
},
},
methods: {
toggleCategory(id) {
const index = this.selectedCategoryIds.indexOf(id)
if (index > -1) {
this.selectedCategoryIds.splice(index, 1)
} else {
this.selectedCategoryIds.push(id)
this.selectedCategoryIds = xor(this.selectedCategoryIds, [id])
if (this.$parentForm) {
this.$parentForm.update(this.model, this.selectedCategoryIds)
}
},
isActive(id) {
const index = this.selectedCategoryIds.indexOf(id)
if (index > -1) {
return true
}
return false
return this.selectedCategoryIds.includes(id)
},
isDisabled(id) {
return !!(this.reachedMaximum && !this.isActive(id))

View File

@ -20,11 +20,38 @@ config.stubs['client-only'] = '<span><slot /></span>'
config.stubs['nuxt-link'] = '<span><slot /></span>'
config.stubs['v-popover'] = '<span><slot /></span>'
const categories = [
{
id: 'cat3',
slug: 'health-wellbeing',
icon: 'medkit',
},
{
id: 'cat12',
slug: 'it-internet-data-privacy',
icon: 'mouse-pointer',
},
{
id: 'cat9',
slug: 'democracy-politics',
icon: 'university',
},
{
id: 'cat15',
slug: 'consumption-sustainability',
icon: 'shopping-cart',
},
{
id: 'cat4',
slug: 'environment-nature',
icon: 'tree',
},
]
describe('ContributionForm.vue', () => {
let wrapper
let postTitleInput
let expectedParams
let deutschOption
let cancelBtn
let mocks
let propsData
@ -109,34 +136,26 @@ describe('ContributionForm.vue', () => {
beforeEach(() => {
wrapper = Wrapper()
wrapper.setData({
form: {
languageOptions: [
{
label: 'Deutsch',
value: 'de',
},
],
},
})
})
describe('CreatePost', () => {
describe('language placeholder', () => {
it("displays the name that corresponds with the user's location code", () => {
it.skip("displays the name that corresponds with the user's location code", () => {
// Well not anymore right? We want the user to save the language
// excplicitly. I'll keep this test if we change our minds
expect(wrapper.find('.ds-select-placeholder').text()).toEqual('English')
})
})
describe('invalid form submission', () => {
it('title and content should not be empty ', async () => {
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
it('title should not be empty', async () => {
await wrapper.vm.updateEditorContent(postContent)
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
@ -144,7 +163,7 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitleTooLong)
await wrapper.vm.updateEditorContent(postContent)
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
@ -152,14 +171,14 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitleTooShort)
await wrapper.vm.updateEditorContent(postContent)
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
it('content should not be empty', async () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.find('.submit-button-for-test').trigger('click')
await wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
@ -167,7 +186,7 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContentTooShort)
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
@ -175,7 +194,7 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContentTooLong)
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
@ -183,7 +202,7 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
@ -192,7 +211,7 @@ describe('ContributionForm.vue', () => {
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
wrapper.vm.form.categoryIds = ['cat4', 'cat9', 'cat15', 'cat27']
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
})
@ -214,43 +233,48 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
categoryIds = ['cat12']
wrapper.find(CategoriesSelect).vm.$emit('updateCategories', categoryIds)
wrapper.find(CategoriesSelect).setData({ categories })
wrapper
.findAll('li')
.at(1)
.trigger('click') // language
await wrapper
.find(CategoriesSelect)
.findAll('button')
.at(1)
.trigger('click')
})
it('creates a post with valid title, content, and at least one category', async () => {
await wrapper.find('.submit-button-for-test').trigger('click')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
})
it("sends a fallback language based on a user's locale", () => {
wrapper.find('.submit-button-for-test').trigger('click')
await wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
})
it('supports changing the language', async () => {
expectedParams.variables.language = 'de'
deutschOption = wrapper.findAll('li').at(0)
deutschOption.trigger('click')
wrapper.find('.submit-button-for-test').trigger('click')
wrapper
.findAll('li')
.at(0)
.trigger('click') // choose German as language
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
})
it('supports adding a teaser image', async () => {
expectedParams.variables.imageUpload = imageUpload
wrapper.find(TeaserImage).vm.$emit('addTeaserImage', imageUpload)
await wrapper.find('.submit-button-for-test').trigger('click')
await wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
})
it("pushes the user to the post's page", async () => {
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
await mocks.$apollo.mutate
expect(mocks.$router.push).toHaveBeenCalledTimes(1)
})
it('shows a success toaster', async () => {
wrapper.find('.submit-button-for-test').trigger('click')
wrapper.find('form').trigger('submit')
await mocks.$apollo.mutate
expect(mocks.$toast.success).toHaveBeenCalledTimes(1)
})
@ -275,11 +299,20 @@ describe('ContributionForm.vue', () => {
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
categoryIds = ['cat12']
wrapper.find(CategoriesSelect).vm.$emit('updateCategories', categoryIds)
wrapper.find(CategoriesSelect).setData({ categories })
wrapper
.findAll('li')
.at(1)
.trigger('click') // language
await wrapper
.find(CategoriesSelect)
.findAll('button')
.at(1)
.trigger('click')
})
it('shows an error toaster when apollo mutation rejects', async () => {
await wrapper.find('.submit-button-for-test').trigger('click')
await wrapper.find('form').trigger('submit')
await mocks.$apollo.mutate
await expect(mocks.$toast.error).toHaveBeenCalledWith('Not Authorised!')
})
@ -345,7 +378,7 @@ describe('ContributionForm.vue', () => {
content: postContent,
language: propsData.contribution.language,
id: propsData.contribution.id,
categoryIds,
categoryIds: ['cat12'],
image,
imageUpload: null,
},
@ -356,19 +389,40 @@ describe('ContributionForm.vue', () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
wrapper.vm.updateEditorContent(postContent)
wrapper.find(CategoriesSelect).vm.$emit('updateCategories', categoryIds)
wrapper.find('.submit-button-for-test').trigger('click')
wrapper
.findAll('li')
.at(0)
.trigger('click') // language
await wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
})
it('supports updating categories', async () => {
const categoryIds = ['cat3', 'cat51', 'cat37']
expectedParams.variables.categoryIds = ['cat12', 'cat3', 'cat15']
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
wrapper.vm.updateEditorContent(postContent)
expectedParams.variables.categoryIds = categoryIds
wrapper.find(CategoriesSelect).vm.$emit('updateCategories', categoryIds)
await wrapper.find('.submit-button-for-test').trigger('click')
wrapper
.findAll('li')
.at(0)
.trigger('click') // language
wrapper.find(CategoriesSelect).setData({ categories })
await wrapper
.find(CategoriesSelect)
.findAll('button')
.at(0)
.trigger('click')
await wrapper
.find(CategoriesSelect)
.findAll('button')
.at(3)
.trigger('click')
await wrapper
.find(CategoriesSelect)
.findAll('button')
.at(4)
.trigger('click')
await wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
})
})

View File

@ -1,5 +1,11 @@
<template>
<ds-form ref="contributionForm" v-model="form" :schema="formSchema">
<ds-form
class="contribution-form"
ref="contributionForm"
v-model="form"
:schema="formSchema"
@submit="submit"
>
<template slot-scope="{ errors }">
<hc-teaser-image :contribution="contribution" @addTeaserImage="addTeaserImage">
<img
@ -22,23 +28,11 @@
autofocus
/>
<ds-text align="right">
<ds-chip v-if="form.title.length < formSchema.title.min" class="checkicon" size="base">
{{ form.title.length }}/{{ formSchema.title.max }}
<ds-icon name="warning" class="colorRed"></ds-icon>
</ds-chip>
<ds-chip
v-else-if="form.title.length < formSchema.title.max"
class="checkicon"
size="base"
color="primary"
>
{{ form.title.length }}/{{ formSchema.title.max }}
<ds-icon name="check"></ds-icon>
</ds-chip>
<ds-chip v-else class="checkicon" size="base" color="danger">
<ds-chip v-if="errors && errors.title" color="danger" size="base">
{{ form.title.length }}/{{ formSchema.title.max }}
<ds-icon name="warning"></ds-icon>
</ds-chip>
<ds-chip v-else size="base">{{ form.title.length }}/{{ formSchema.title.max }}</ds-chip>
</ds-text>
<client-only>
<hc-editor
@ -48,57 +42,39 @@
@input="updateEditorContent"
/>
<ds-text align="right">
<ds-chip
v-if="form.contentLength < formSchema.content.min"
class="checkicon"
size="base"
>
{{ form.contentLength }}
<ds-icon name="warning" class="colorRed"></ds-icon>
<ds-chip v-if="errors && errors.content" color="danger" size="base">
{{ contentLength }}
<ds-icon name="warning"></ds-icon>
</ds-chip>
<ds-chip v-else class="checkicon" size="base" color="primary">
{{ form.contentLength }}
<ds-icon name="check"></ds-icon>
<ds-chip v-else size="base">
{{ contentLength }}
</ds-chip>
</ds-text>
</client-only>
<ds-space margin-bottom="small" />
<hc-categories-select
model="categoryIds"
@updateCategories="updateCategories"
:existingCategoryIds="form.categoryIds"
/>
<hc-categories-select model="categoryIds" :existingCategoryIds="form.categoryIds" />
<ds-text align="right">
<ds-chip v-if="form.categoryIds.length === 0" class="checkicon checkicon_cat" size="base">
<ds-chip v-if="errors && errors.categoryIds" color="danger" size="base">
{{ form.categoryIds.length }} / 3
<ds-icon name="warning" class="colorRed">></ds-icon>
</ds-chip>
<ds-chip v-else class="checkicon checkicon_cat" size="base" color="primary">
{{ form.categoryIds.length }} / 3
<ds-icon name="check"></ds-icon>
<ds-icon name="warning"></ds-icon>
</ds-chip>
<ds-chip v-else size="base">{{ form.categoryIds.length }} / 3</ds-chip>
</ds-text>
<ds-flex class="contribution-form-footer">
<ds-flex-item>
<ds-space margin-bottom="small" />
<ds-select
model="language"
:options="form.languageOptions"
:options="languageOptions"
icon="globe"
:placeholder="form.languageDefault"
:placeholder="$t('contribution.languageSelectText')"
:label="$t('contribution.languageSelectLabel')"
@input.native="updateLanguage"
/>
</ds-flex-item>
</ds-flex>
<ds-text align="right">
<ds-chip v-if="form.language !== null" size="base" color="primary">
{{ form.language.label }}
<ds-icon name="check"></ds-icon>
</ds-chip>
<ds-chip v-else size="base">
{{ $t('contribution.languageSelectLabel') }}
<ds-icon name="warning" class="colorRed"></ds-icon>
<ds-chip v-if="errors && errors.language" size="base" color="danger">
<ds-icon name="warning"></ds-icon>
</ds-chip>
</ds-text>
<ds-space />
@ -111,15 +87,7 @@
>
{{ $t('actions.cancel') }}
</ds-button>
<ds-button
class="submit-button-for-test"
type="submit"
icon="check"
:loading="loading"
:disabled="failsValidations || errors"
primary
@click.prevent="submit"
>
<ds-button type="submit" icon="check" :loading="loading" :disabled="errors" primary>
{{ $t('actions.save') }}
</ds-button>
</div>
@ -151,75 +119,84 @@ export default {
contribution: { type: Object, default: () => {} },
},
data() {
const languageOptions = orderBy(locales, 'name').map(locale => {
return { label: locale.name, value: locale.code }
})
const formDefaults = {
title: '',
content: '',
teaserImage: null,
image: null,
language: null,
categoryIds: [],
}
let id = null
let slug = null
const form = { ...formDefaults }
if (this.contribution && this.contribution.id) {
id = this.contribution.id
slug = this.contribution.slug
form.title = this.contribution.title
form.content = this.contribution.content
form.image = this.contribution.image
form.language =
this.contribution && this.contribution.language
? languageOptions.find(o => this.contribution.language === o.value)
: null
form.categoryIds = this.categoryIds(this.contribution.categories)
}
return {
form: {
title: '',
content: '',
contentLength: 0,
teaserImage: null,
image: null,
language: null,
languageOptions: [],
languageDefault: this.$t('contribution.languageSelectText'),
selectedLanguage: '',
categoryIds: [],
},
form,
formSchema: {
title: { required: true, min: 3, max: 100 },
content: { required: true, min: 3 },
content: {
required: true,
min: 3,
transform: content => {
return this.$filters.removeHtml(content)
},
},
categoryIds: {
type: 'array',
required: true,
validator: (rule, value) => {
const errors = []
if (!(value && value.length >= 1 && value.length <= 3)) {
errors.push(new Error(this.$t('common.validations.categories')))
}
return errors
},
},
language: { required: true },
},
id: null,
languageOptions,
id,
slug,
loading: false,
slug: null,
users: [],
contentMin: 3,
failsValidations: true,
hashtags: [],
}
},
watch: {
contribution: {
immediate: true,
handler: function(contribution) {
if (!contribution || !contribution.id) {
return
}
this.id = contribution.id
this.slug = contribution.slug
this.form.title = contribution.title
this.form.content = contribution.content
this.form.image = contribution.image
this.form.categoryIds = this.categoryIds(contribution.categories)
this.manageContent(this.form.content)
},
},
},
computed: {
locale() {
const locale =
this.contribution && this.contribution.language
? locales.find(loc => this.contribution.language === loc.code)
: locales.find(loc => this.$i18n.locale() === loc.code)
return locale.name
contentLength() {
return this.$filters.removeHtml(this.form.content).length
},
...mapGetters({
currentUser: 'auth/user',
}),
},
mounted() {
this.availableLocales()
},
methods: {
submit() {
const { title, content, image, teaserImage, categoryIds } = this.form
let language
if (this.form.language) {
language = this.form.language.value
} else if (this.contribution && this.contribution.language) {
language = this.contribution.language
} else {
language = this.$i18n.locale()
}
const {
language: { value: language },
title,
content,
image,
teaserImage,
categoryIds,
} = this.form
this.loading = true
this.$apollo
.mutate({
@ -238,7 +215,6 @@ export default {
this.loading = false
this.$toast.success(this.$t('contribution.success'))
const result = data[this.id ? 'UpdatePost' : 'CreatePost']
this.failedValidations = false
this.$router.push({
name: 'post-id-slug',
@ -248,53 +224,16 @@ export default {
.catch(err => {
this.$toast.error(err.message)
this.loading = false
this.failedValidations = true
})
},
updateEditorContent(value) {
// TODO: Do smth????? what is happening
this.$refs.contributionForm.update('content', value)
this.manageContent(value)
},
manageContent(content) {
let str = content.replace(/<\/?[^>]+(>|$)/gm, '')
this.form.contentLength = str.length
this.validatePost()
},
availableLocales() {
orderBy(locales, 'name').map(locale => {
this.form.languageOptions.push({ label: locale.name, value: locale.code })
})
},
updateCategories(ids) {
this.form.categoryIds = ids
this.validatePost()
},
updateLanguage() {
this.form.selectedLanguage = this.form.language.label
this.validatePost()
},
addTeaserImage(file) {
this.form.teaserImage = file
},
categoryIds(categories) {
let categoryIds = []
categories.map(categoryId => {
categoryIds.push(categoryId.id)
})
return categoryIds
},
validatePost() {
const passesContentValidations = this.form.contentLength >= this.contentMin
const passesCategoryValidations =
this.form.categoryIds.length > 0 && this.form.categoryIds.length <= 3
const passedLanguageValidation = this.form.language !== null
this.failsValidations = !(
passesContentValidations &&
passesCategoryValidations &&
passedLanguageValidation
)
return categories.map(c => c.id)
},
},
apollo: {
@ -349,14 +288,10 @@ export default {
padding-right: 0;
}
}
.checkicon {
cursor: default;
top: -18px;
}
.checkicon_cat {
top: -58px;
}
.colorRed {
color: red;
.contribution-form {
.ds-chip {
cursor: default;
}
}
</style>

View File

@ -45,6 +45,7 @@ export const postFragment = lang => gql`
deleted
slug
image
language
author {
...user
}

View File

@ -434,7 +434,8 @@
"reportContent": "Melden",
"validations": {
"email": "muss eine gültige E-Mail Adresse sein",
"url": "muss eine gültige URL sein"
"url": "muss eine gültige URL sein",
"categories": "es müssen eine bis drei Kategorien ausgewählt werden"
}
},
"actions": {

View File

@ -435,7 +435,8 @@
"reportContent": "Report",
"validations": {
"email": "must be a valid e-mail address",
"url": "must be a valid URL"
"url": "must be a valid URL",
"categories": "at least one and at most three categories must be selected"
}
},
"actions": {

View File

@ -10,41 +10,37 @@
<script>
import HcContributionForm from '~/components/ContributionForm/ContributionForm'
import PostQuery from '~/graphql/PostQuery'
import { mapGetters } from 'vuex'
export default {
components: {
HcContributionForm,
},
computed: {
user() {
return this.$store.getters['auth/user']
},
author() {
return this.contribution ? this.contribution.author : {}
},
contribution() {
return this.Post ? this.Post[0] : {}
},
...mapGetters({
user: 'auth/user',
}),
},
watch: {
contribution() {
if (this.author.id !== this.user.id) {
throw new Error(`You can't edit that!`)
}
},
},
apollo: {
Post: {
query() {
return PostQuery(this.$i18n)
async asyncData(context) {
const {
app,
store,
error,
params: { id },
} = context
let client = app.apolloProvider.defaultClient
const {
data: {
Post: [contribution],
},
variables() {
return {
id: this.$route.params.id,
}
},
fetchPolicy: 'cache-and-network',
},
} = await client.query({
query: PostQuery(app.$i18n),
variables: { id },
})
if (contribution.author.id !== store.getters['auth/user'].id) {
error({ statusCode: 403, message: "You can't edit that!" })
}
return { contribution }
},
}
</script>