Send object as get parameter with Axios - javascript

The API expects the following GET request:
/resource?labels[team1]=corona&labels[team2]=virus
My issue is to generate this URL using the Axios params option.
I tried the following params structures and they both generate the wrong url:
{
labels: {
team1: 'corona',
team2: 'virus'
}
}
{
labels: [
team1: 'corona',
team2: 'virus'
]
}
I at least thought it would work with the string indexed array but that generates no get params at all.
So, can anyone tell me how to generate the desired URL?

The solution was to use the paramsSerializer with the same setup as in the axios readme. And I used the first params object from my post above..
paramsSerializer: (params) => {
return qs.stringify(params, { arrayFormat: 'brackets' });
}

Related

Is there specific way to do an if-else statement in javascript for mongodb using mongoose?

I want to only run a statement only if the object is not null. If it is null I want to not do anything. I want to be sure if there is a proper way to achieve this. For example I tried it on MongoDB Playground and it did not work. Here is the link to playground: https://mongoplayground.net/p/yOmRxML88zi
Here is the if-else statement I want to run:
db.collection.aggregate([
{...},
service_type ? { $match: { serviceType: service_type } } : null,
{...},
]);
So if the service_type is not null run the statement else skip to next object in the aggregation. What I want to do in this occasion is get the list of everything in database (objects) that contain certain service type given by the user.
The schema looks something like this:
const sellerSchema = new mongoose.Schema({
user_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
...,
serviceType: [{ String }],
});
If you're using Mongoose, I suppose you're writing your app using Javascript or TypeScript.
What prevent you, then, from building your query like this?
const aggregatePipeline = [];
if (service_type) aggregatePipeline.push({ $match: { serviceType: service_type }});
...
db.collection.aggregate(aggregatePipeline).exec()

SUPABASE/JavsScript: how to DELETE user metadata?

Is there a way to delete user metadata in Supabase? They offer update() option, but it seems it works as patch request, so I can't find a way to delete it.
Here's their code:
```const { user, error } = await supabase.auth.update({
data: { hello: 'world' }
});```
I tried to do this:
```const { user, error } = await supabase.auth.update({
data: {}
});```
But is doesn't do anything.
Can metadata be deleted?
Thanks
It is possible to set the metadata field to an empty JSON object (i.e. {}) but, currently, there is no way to set it to NULL. Also, you would need to know all the fields that are already stored in the metadata because you need to remove each one explicitly.
If this works for your scenario, the way to do it is to send a data object where each field that you want removed has a value of null.
For example, if you have the following JSON in your metadata: { 'field1': 2, 'field2': 'something' }, you can set the metadata to an empty JSON object like this:
supabase.auth.update({ 'data': { 'field1': null, 'field2': null } });

Axios sends an array of strings instead of an array of objects

Axios sends an array of strings instead of an array of objects. I have an array of objects that contains data about the event. I'm trying to send a request to the server via axios, but I get a array of strings insteenter image description heread of objects at the output
let data = {
title: 'Game',
subject: 'Some subject',
date: ['01/01/2021','01/01/2021'],
years: ['1970', '1970'],
address: 'None',
ages: [
{
title: 'Men',
weights: [{page: 0, title: '60'}]
}
]
};
api.Create({
params: data
}).then(function (response) {
console.log(response.data);
})
.catch(function (err) {
console.log(err);
});
api response
try to:
console.log(JSON.parse(response.data))
What you get back from the server is string. you need to parse it.
When you send data to and from a server, it is sent as a 'serialized' string, usually JSON format
That's how server responses work
It turned out to be an incorrect request. I used GET to pass the object, instead of POST, so it converts it to a string. I want to notice that there is an evil community on this site.

Cypress request : empty array in body

I'm finding myself in some troubles while testing my API with Cypress. (I'm using version 2.1.0)
I am sending a request to my endpoint, and want to verify how it is reacting when I am sending an empty array as a parameter. The problem is that somehow, Cypress must be parsing the body I am giving him, and removing the empty array.
My code is the following :
cy.request({
method: 'PUT',
url,
form: true,
body: {
name: 'Name',
subjects: []
}
})
.then((response) => {
expect(response.body).to.have.property('subjects');
const { subjects } = response.body;
expect(subjects.length).to.eq(0);
});
// API receives only the parameter name, and no subjects
When I am sending an empty array of subjects, the endpoint will delete all the associated subjects, and return the object with an empty array of subjects. It is working as it should, and my software in use is working as it should.
When Cypress is sending this request, the endpoint does not receive the parameter subjects. Which is for me a very different thing : I should not touch the subjects in this case.
Is there a way to avoid this "rewriting" by Cypress and send the body as I write it ?
The test works when setting form: false.
it.only('PUTs a request', () => {
const url = 'http://localhost:3000/mythings/2'
cy.request({
method: 'PUT',
url: url,
form: false,
body: {
name: 'Name',
subjects: []
}
})
.then((response) => {
expect(response.body).to.have.property('subjects');
const {
subjects
} = response.body;
expect(subjects.length).to.eq(0);
});
})
I set up a local rest server with json-server to check out the behavior.
If I try to PUT a non-empty array with form: true
cy.request({
method: 'PUT',
url: url,
form: true,
body: {
name: 'Name',
subjects: ['x']
}
})
looking at db.json after the test has run, I see the item index migrating into the key,
"mythings": [
{
"name": "Name",
"subjects[0]": "x",
"id": 2
}
],
so perhaps form means simple properties only.
Changing to form: false gives a proper array
{
"mythings": [
{
"name": "Name",
"subjects": ['x'],
"id": 2
}
],
}
which can then be emptied out by posting an empty array.

Elasticsearch - return only the source data part

I want to get only the json data from elasticsearch through node js.
I used
client.search({
index: 'dashboard',
type: 'test',
filterPath: 'hits.hits._source',
body: {
query: { match_all: {} }
}
})
It will show the result as:
{"_source":{"datatime":"2017-08-21 16:03:00","time_of_day":11},{"_source":{"datatime":"2017-08-21 16:03:00","time_of_day":222}]
May I know how to select only the data part in the source through node js, without "_source"? Only {"datatime":"2017-08-21 16:03:00","time_of_day":11},{"datatime":"2017-08-21 16:03:00","time_of_day":222}
Ok, solved.
can use hits.hits._source.theDataName, such as hits.hits._source.datatime , it will show "datatime":"2017-08-21 16:03:00"

Categories