Vuex: dispatch with array as argument - vuex

Is it possible to have an array in the payload of dispatch method in vuex ?
Below, I have a table name string, an id number, but the path array in the payload gives me the array length as a result.
this.$store.dispatch('DESTROY_ENTRY', { table, id, path }).then(response => {
console.log(response)
}, error => {
console.log(error)
})
===
After NikosM comment, I realized that if I set this:
this.$store.dispatch('DESTROY_ENTRY', { table, id, path2: { 'a':'foo', 'b':'bar' } })
I get this for path:
path2: {a: "foo", b: "bar"}
But it doesn't accept my path array.

Related

ApolloServer Wrong response value {key: value} !== /"{key: value}"/

I have simple __resolveType with returns given object
const Resolvers = {
Foo: {
__resolveType(obj: Objct) {
console.log(typeof obj) // Object
return obj
},
},
Query: {
Bar: () => data
}
}
And I am getting this error
Any idea how to get rid of these backslashes
I don't even know why they appear and what that mean
packages.json

Validate request body separately from request as a whole

I have a question for validating a PUT request. The body of the request is an array of objects. I want the request to succeed if the body contains an array of at least length one, but I also need to do a separate validation on each object in the array and pass that back in the response. So my put body would be:
[1, 2, {id: "thirdObject"}]
The response should be 200 even though the first two items are not even objects. The request just needs to succeed if an array of length 1 is passed in the body. The response needs to be something like:
[{id: firstObject, status: 400, error: should be object}, {id: secondObject, status: 400, error: should be object}, { id: thirdObject, status: 204 }]
Currently I am validating the body as such with fluent schema:
body: S.array().items(myObjectSchema)
.minItems(1)
Which will result in a 400 if any of the items in the body don’t match the myObjectSchema. Was wondering if you have any idea how to achieve this?
The validation doesn't tell you if a schema is successful (eg { id: thirdObject, status: 204 }), so you need to manage it by yourself.
To do that, you need to create an error handler to read the validation error and merge with the request body:
const fastify = require('fastify')()
const S = require('fluent-schema')
fastify.put('/', {
handler: () => { /** this will never executed if the schema validation fail */ },
schema: {
body: S.array().items(S.object()).minItems(1)
}
})
const errorHandler = (error, request, reply) => {
const { validation, validationContext } = error
// check if we have a validation error
if (validation) {
// here the validation error
console.log(validation)
// here the body
console.log(request.body)
reply.send(validation)
} else {
reply.send(error)
}
}
fastify.setErrorHandler(errorHandler)
fastify.inject({
method: 'PUT',
url: '/',
payload: [1, 2, { id: 'thirdObject' }]
}, (_, res) => {
console.log(res.json())
})
This will log:
[
{
keyword: 'type',
dataPath: '[0]',
schemaPath: '#/items/type',
params: { type: 'object' },
message: 'should be object'
},
{
keyword: 'type',
dataPath: '[1]',
schemaPath: '#/items/type',
params: { type: 'object' },
message: 'should be object'
}
]
[ 1, 2, { id: 'thirdObject' } ]
As you can see, thanks to validation[].dataPath you are able to understand which elements of the body array is not valid and merge the data to return your info.
Consider that the handler will be not executed in this scenario. If you need to execute it regardless the validation, you should do the validation job in a preHandler hook and avoid the default schema validation checks (since it is blocking)
edit
const fastify = require('fastify')()
const S = require('fluent-schema')
let bodyValidator
fastify.decorateRequest('hasError', function () {
if (!bodyValidator) {
bodyValidator = fastify.schemaCompiler(S.array().items(S.object()).minItems(1).valueOf())
}
const valid = bodyValidator(this.body)
if (!valid) {
return bodyValidator.errors
}
return true
})
fastify.addHook('preHandler', (request, reply, done) => {
const errors = request.hasError()
if (errors) {
console.log(errors)
// show the same errors as before
// you can merge here or set request.errors = errors to let the handler read them
reply.send('here merge errors and request.body')
return
}
done() // needed to continue if you don't reply.send
})
fastify.put('/', { schema: { body: S.array() } }, (req, reply) => {
console.log('handler')
reply.send('handler')
})
fastify.inject({
method: 'PUT',
url: '/',
payload: [1, 2, { id: 'thirdObject' }]
}, (_, res) => {
console.log(res.json())
})
I don't know the schema syntax you are using, but using draft 7 of the JSON Schema (https://json-schema.org/specification-links.html, and see also https://json-schema.org/understanding-json-schema for some reference material), you can do:
{
"type": "array",
"minItems": 1
}
If you want to ensure that at least one, but not necessarily all items match your object type, then add the "contains" keyword:
{
...,
"contains": ... reference to your object schema here
}

Axios post request with multiple parameters in vuex action

Fetching API data with axios in vuex action:
actions: {
login ({commit}, payload) {
axios.post(globalConfig.TOKEN_URL, {
payload
})
.then((resp) => {
commit('auth_success', resp.data)
})
.catch((err) => {
console.log(err)
})
},
}
Component's method for sending the data:
methods: {
authChatClient () {
let payload = {
name: this.clientFio,
number: this.clientNumber
}
this.$store.dispatch('login', payload)
},
}
However it won't work, since payload is an object, wrapped in a payload object. Is it possible to send multiple parameters from component's method to a vuex action?
Post request is looking like this: payload: {name: "aaa", number: "111"}
Vuex only allows the use of 1 parameter to an action. However, if I understand your question correctly, you can send multiple parameters to a vuex action if they are wrapped in an object. Example:
login({commit}, {name, number /*, ...more here*/}) {
axios.post(globalConfig.TOKEN_URL, {
name: name,
number: number,
/* more parameters here */
})
/* ... */
}
And you can call it with:
methods: {
authChatClient () {
let payload = {
name: this.clientFio,
number: this.clientNumber,
/* more parameters */
}
this.$store.dispatch('login', payload)
},
}

get single record through axios in vuex store

I would like to return a single record from my back end using a Vuex store module in Nuxt.
I have the following in my component, which passes the value i want
( which is the $route.params.caseId )
created () {
this.$store.dispatch('cases/getCase', $route.params.caseId );
},
I pass the $route.params.caseId into my getCase action in my vuex store module as follows
getCase ({ commit, context }, data) {
return axios.get('http' + data + '.json')
.then(res => {
const convertcase = []
for (const key in res.data) {
convertcase.push({ ...res.data[key], id: key })
}
//console.log(res.data) returns my record from firebase (doesnt display the key though in the array, just the fields within the firebase record, but assume this is expected?
commit('GET_CASE', convertcase)
})
.catch(e => context.error(e));
},
the convert case is to extract the id from firebase key and add it to my array as id field (Is this correct for a single result from firebase in this way?)
My mutation
// Get Investigation
GET_CASE(state, caseId) {
state.caseId = caseId;
},
Now when I use Case Name: {{ caseId.case_name }} I'm not getting any result,
I'm not getting an error though, any thoughts on what i am doing wrong please
Many Thank
You can pass more data to an action like you did in the dispatch method and later access them normally.
Note the data parameter of the getCase function, in your example data === $route.params.caseId
//Load single investigation
getCase ({ commit, context }, data) {
return axios.get('http' + investigationID + '.json')
.then(res => {
const convertcase = []
for (const key in res.data) {
convertcase.push({ ...res.data[key], id: key })
}
commit('GET_CASE', convertcase)
})
.catch(e => context.error(e));
},
In case you want to use promises, check out the exemple below of a action in my app that fetches a single BLOG_POST
let FETCH_BLOG_POST = ({commit, state}, { slug }) => {
return new Promise((resolve, reject) => {
fetchBlogPost(slug, state.axios)
.then((post) => {
console.log("FETCH_BLOG_POSTS", post.data.data)
commit('SET_BLOG_POST', post.data.data)
resolve(post.data)
})
.catch((error) => {
console.log("FETCH_BLOG_POST.catch")
reject(error)
})
});
}

adding a query to an axios get request

I am trying to restrict what gets returned by my axios get request.
I have a firebase backend and in my data i have a field called case_name, I have added a few records with the name Test and thought i could run the following in a get request to restrict my results to just those where case_name is equal to test, but it still returns all records
loadCase ({ commit, context }) {
return axios.get('http', {
params: {
case_name: 'Test'
}
})
.then(res => {
const convertcase = []
for (const key in res.data) {
convertcase.push({ ...res.data[key], id: key })
}
commit('listcase', convertcase)
})
.catch(e => context.error(e));
},
Can anyone tell me what im doing wrong please as cant find anything to help me at the moment
my returned object is
data: {…}
​​
"-LFXvk9yY5c-O8yIdf8k": Object { case_name: "Test", case_status: "live", case_summary: "This is some summary content", … }
​​
"-LFXwmv6eHqZs8jndNay": Object { case_name: "case 2", case_status: "live", case_summary: "dasdasdasdasd\nasd\ndasd\na\nsdasdasd", … }
​​
"-LFc2t9V7LVqnLAlIjoU": Object { case_name: "Test", case_status: "live", case_summary: "this is just another summary", … }
Thanks