Merge pull request #2160 from Human-Connection/2119_Create_Post_consistent_form_input_validation

🍰 2119-Fix Contribution  consistent form input validation
This commit is contained in:
mattwr18 2019-11-19 00:27:48 +01:00 committed by GitHub
commit c775884c59
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 275 additions and 259 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

@ -5,6 +5,7 @@
<ds-flex-item>
<ds-button
size="small"
:data-test="categoryButtonsId(category.id)"
@click.prevent="toggleCategory(category.id)"
:primary="isActive(category.id)"
:disabled="isDisabled(category.id)"
@ -28,16 +29,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,39 +56,22 @@ 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))
},
categoryButtonsId(categoryId) {
return `category-buttons-${categoryId}`
},
},
apollo: {
Category: {

View File

@ -20,15 +20,45 @@ 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
let categoryIds
let wrapper,
postTitleInput,
expectedParams,
cancelBtn,
mocks,
propsData,
categoryIds,
englishLanguage,
deutschLanguage,
dataPrivacyButton
const postTitle = 'this is a title for a post'
const postTitleTooShort = 'xx'
let postTitleTooLong = ''
@ -36,11 +66,6 @@ describe('ContributionForm.vue', () => {
postTitleTooLong += 'x'
}
const postContent = 'this is a post'
const postContentTooShort = 'xx'
let postContentTooLong = ''
for (let i = 0; i < 2001; i++) {
postContentTooLong += 'x'
}
const imageUpload = {
file: {
filename: 'avataar.svg',
@ -109,90 +134,59 @@ 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", () => {
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')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
beforeEach(async () => {
wrapper.find(CategoriesSelect).setData({ categories })
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
englishLanguage = wrapper.findAll('li').filter(language => language.text() === 'English')
englishLanguage.trigger('click')
dataPrivacyButton = await wrapper
.find(CategoriesSelect)
.find('[data-test="category-buttons-cat12"]')
dataPrivacyButton.trigger('click')
})
it('title should not be empty', async () => {
await wrapper.vm.updateEditorContent(postContent)
wrapper.find('.submit-button-for-test').trigger('click')
postTitleInput.setValue('')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
it('title should not be too long', async () => {
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()
})
it('title should not be too short', async () => {
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')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
it('content should not be too short', async () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContentTooShort)
wrapper.find('.submit-button-for-test').trigger('click')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
it('content should not be too long', async () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContentTooLong)
wrapper.find('.submit-button-for-test').trigger('click')
await wrapper.vm.updateEditorContent('')
await wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
it('should have at least one category', async () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
await wrapper.vm.updateEditorContent(postContent)
wrapper.find('.submit-button-for-test').trigger('click')
dataPrivacyButton = await wrapper
.find(CategoriesSelect)
.find('[data-test="category-buttons-cat12"]')
dataPrivacyButton.trigger('click')
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).not.toHaveBeenCalled()
})
it('should have not have more than three categories', async () => {
postTitleInput = wrapper.find('.ds-input')
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 +208,51 @@ 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 })
englishLanguage = wrapper.findAll('li').filter(language => language.text() === 'English')
englishLanguage.trigger('click')
dataPrivacyButton = await wrapper
.find(CategoriesSelect)
.find('[data-test="category-buttons-cat12"]')
dataPrivacyButton.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')
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))
})
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('content is valid with just a link', async () => {
await wrapper.vm.updateEditorContent(
'<a href="https://www.youtube.com/watch?v=smoEelV6FUk" target="_blank"></a>',
)
wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledTimes(1)
})
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 +277,17 @@ 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 })
englishLanguage = wrapper.findAll('li').filter(language => language.text() === 'English')
englishLanguage.trigger('click')
dataPrivacyButton = await wrapper
.find(CategoriesSelect)
.find('[data-test="category-buttons-cat12"]')
dataPrivacyButton.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!')
})
@ -341,11 +349,11 @@ describe('ContributionForm.vue', () => {
expectedParams = {
mutation: PostMutations().UpdatePost,
variables: {
title: postTitle,
content: postContent,
title: propsData.contribution.title,
content: propsData.contribution.content,
language: propsData.contribution.language,
id: propsData.contribution.id,
categoryIds,
categoryIds: ['cat12'],
image,
imageUpload: null,
},
@ -353,22 +361,20 @@ describe('ContributionForm.vue', () => {
})
it('calls the UpdatePost apollo mutation', async () => {
postTitleInput = wrapper.find('.ds-input')
postTitleInput.setValue(postTitle)
expectedParams.variables.content = postContent
wrapper.vm.updateEditorContent(postContent)
wrapper.find(CategoriesSelect).vm.$emit('updateCategories', categoryIds)
wrapper.find('.submit-button-for-test').trigger('click')
await wrapper.find('form').trigger('submit')
expect(mocks.$apollo.mutate).toHaveBeenCalledWith(expect.objectContaining(expectedParams))
})
it('supports updating categories', async () => {
const categoryIds = ['cat3', 'cat51', 'cat37']
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')
expectedParams.variables.categoryIds.push('cat3')
wrapper.find(CategoriesSelect).setData({ categories })
const healthWellbeingButton = await wrapper
.find(CategoriesSelect)
.find('[data-test="category-buttons-cat3"]')
healthWellbeingButton.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
@ -21,7 +27,13 @@
name="title"
autofocus
/>
<small class="smallTag">{{ form.title.length }}/{{ formSchema.title.max }}</small>
<ds-text align="right">
<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
:users="users"
@ -29,27 +41,43 @@
:hashtags="hashtags"
@input="updateEditorContent"
/>
<small class="smallTag">{{ form.contentLength }}</small>
<ds-text align="right">
<ds-chip v-if="errors && errors.content" color="danger" size="base">
{{ contentLength }}
<ds-icon name="warning"></ds-icon>
</ds-chip>
<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="errors && errors.categoryIds" color="danger" size="base">
{{ form.categoryIds.length }} / 3
<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 :width="{ base: '10%', sm: '10%', md: '10%', lg: '15%' }" />
<ds-flex-item :width="{ base: '80%', sm: '30%', md: '30%', lg: '20%' }">
<ds-flex-item :width="{ lg: '50%', md: '50%', sm: '100%' }" />
<ds-flex-item>
<ds-space margin-bottom="small" />
<ds-select
model="language"
:options="form.languageOptions"
:options="languageOptions"
icon="globe"
:placeholder="locale"
:placeholder="$t('contribution.languageSelectText')"
:label="$t('contribution.languageSelectLabel')"
/>
</ds-flex-item>
</ds-flex>
<ds-text align="right">
<ds-chip v-if="errors && errors.language" size="base" color="danger">
<ds-icon name="warning"></ds-icon>
</ds-chip>
</ds-text>
<ds-space />
<div slot="footer" style="text-align: right">
<ds-button
@ -60,15 +88,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>
@ -100,73 +120,78 @@ 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: [],
categoryIds: [],
},
form,
formSchema: {
title: { required: true, min: 3, max: 100 },
content: [{ required: true }],
content: { required: true },
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({
@ -185,7 +210,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',
@ -195,45 +219,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) {
// filter HTML out of content value
const str = content.replace(/<\/?[^>]+(>|$)/gm, '')
// Set counter length of text
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()
},
addTeaserImage(file) {
this.form.teaserImage = file
},
categoryIds(categories) {
const 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
this.failsValidations = !(passesContentValidations && passesCategoryValidations)
return categories.map(c => c.id)
},
},
apollo: {
@ -288,4 +283,10 @@ export default {
padding-right: 0;
}
}
.contribution-form {
.ds-chip {
cursor: default;
}
}
</style>

View File

@ -463,7 +463,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": {
@ -608,7 +609,8 @@
"filterFollow": "Beiträge filtern von Usern denen ich folge",
"filterALL": "Alle Beiträge anzeigen",
"success": "Gespeichert!",
"languageSelectLabel": "Sprache",
"languageSelectLabel": "Sprache deines Beitrags",
"languageSelectText": "Sprache wählen",
"categories": {
"infoSelectedNoOfMaxCategories": "{chosen} von {max} Kategorien ausgewählt"
},

View File

@ -464,7 +464,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": {
@ -609,7 +610,8 @@
"filterFollow": "Filter contributions from users I follow",
"filterALL": "View all contributions",
"success": "Saved!",
"languageSelectLabel": "Language",
"languageSelectLabel": "Language of your contribution",
"languageSelectText": "Select Language",
"categories": {
"infoSelectedNoOfMaxCategories": "{chosen} of {max} categories selected"
},

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