How to properly convert json array in axios query parameter? - javascript

i struggle to do something that look simple with axios :
Here is my axios query :
axios.get('/consumption_reports', {
params: {
exists: {
energyDeliveryPoint : false
}
}
})
The result is this query :
consumption_reports?exists={"energyDeliveryPoint":false}
When i would like this result :
consumption_reports?exists[energyDeliveryPoint]=false
I tried many different solution but could not found the one that works.
I look forward any answer that keep code simple.
PS : I do not want to hard code the url with my desired behavior.

It works with Axios 1.x
import axios from 'axios';
const {data} = await axios.get('http://httpbin.org/get', {
params: {
exists: {
energyDeliveryPoint : false
}
}
});
console.log(axios.VERSION, data.url); // 1.3.0 http://httpbin.org/get?exists[energyDeliveryPoint]=false

I finally found myself, in that case i have no choice to do this :
axios.get('/consumption_reports', {
params: {
"exists[energyDeliveryPoint]": false
}
})

Related

Getting Parsing error: Unexpected token, expected "," in Vue

I am trying to do an axios request but whatever I do I get the same error message.
The message is:
Parsing error: Unexpected token, expected ",". The error points at axios.get (it points at the dot between "axios" and "get" in the error message). It gives the same message if I put something like console.log in the code.
I am basically just using a regular default vue project and the only thing I have done is to add the following code in HelloWorld.vue.
<script type="text/javascript">
import axios from 'axios';
// const axios = require('axios');
export default {
name: 'HelloWorld', // console.log("hi"),
props: {
msg: String //response
},
methods: {
axios.get('https://swapi.co/api/people/1')
.then(function(response){
console.log(response)
})
}
}
</script>
Can someone please tell me why this error keeps coming up, I am guessing this is pretty simple but I am losing my mind at this point. Thank you
You won't be able to access your axios method, since it isn't actually being declared as a function. You can write vue methods in two ways, both equivalent (to my knowledge).
export default {
data() {
item: []
},
methods: {
getStarWarsCharacters() {
// axios call goes here
}
}
}
Other way is like this:
export default {
data() {
item: []
},
methods: {
getStarWarsCharacters: () => {
// axios call goes here
}
}
}
I suspect that if you write it in the first way, Vue is actually converting to the second.
axios must be globalized in your root file.
const axios = require('axios');
global.axios = axios;

Jasmine Data Provider is not working (jasmine_data_provider_1.using is not a function)

I am trying to achieve Data Driven testing in my project by using jasmine data providers.
I have a data.ts file like below
export const hardshipTestData = {
scenarios: {
scenario1: {
isHome: 'Yes'
},
scenario2: {
isHome: 'No'
}
}
};
I am using above data in spec file
import { using } from 'jasmine-data-provider';
import { hardshipTestData } from '../../data/testdata';
using(hardshipTestData.scenarios, function (data, description) {
it('testing data providers', () => {
console.log(data.isHome);
});
});
My issue here is when I am trying to write data. intelligence is not even giving the option isHome. When I enforce it and run the test I am getting the following error
TestSuite encountered a declaration exception
configuration-parser.js:48
- TypeError: jasmine_data_provider_1.using is not a function
any help is appreciated
You need to change import type. Try to replace:
import { using } from 'jasmine-data-provider';
with:
const using = require('jasmine-data-provider');
Also, keep in mind that firstly should be describe block:
describe('example test', () => {
using(hardshipTestData.scenarios, (data) => {
it('should calc with operator -', () => {
console.log(data.isHome);
});
});
});
Adding to Oleksii answer, his answer is for typescript.
but If you want to use in plain javascript use below:
Add below in your code:
var using = require('jasmine-data-provider');
Example:
var jasminedatasetobj = require("./jasmineDataDrivenData");
var using = require('jasmine-data-provider');
using(jasminedatasetobj.datadrive, function (data, description) {
it('Open NonAngular js website Alerts', async() => {
await browser.get("https://qaclickacademy.github.io/protocommerce/");
element(by.name("name")).sendKeys(data.name);
});
});
You might need to give full path of Jasmine data provider for plain javascripts to avoid module not found error.
var jsondataobj = require('../../../../config/Jsoninput.json');//define the data source location
var using = require('C:/Users/sam/AppData/Roaming/npm/node_modules/jasmine-data-provider');
describe("Test Jasmine Data provider",function(){
you need to declare the variable for "jasmine-data-provider" , because import can use to import the properties/classes.
instead of using variable you can give any name to the varible (I tried use "post" instead of "using" and it is still working as expected)
your code should be like
import { hardshipTestData } from "../Test";
const using = require("jasmine-data-provider");
describe("Login TestCases", () => {
using(hardshipTestData.scenarios, (alldata: any, alldesc: any) => {
it("login with different credentials", async () => {
console.log(data.isHome);
})
})
})
this will resolve you problem.

Ember convert PATCH call to PUT

I am using ember 2.18, in this the update requests are PATCH. However, the backend is in SAILS and it does not support PATCH. Hence, I have to convert patch request to PUT.
I saw this issue and people seems to have solved it there. But it does not work for me. The code is as follows:
import App from './../app';
import DS from "ember-data";
import { computed } from "#ember/object";
import { camelize } from '#ember/string';
import JSONAPIAdapter from "ember-data/adapters/json-api";
export default DS.JSONAPIAdapter.extend({
coalesceFindRequests: true,
host: App.GPT.Configuration.restServer,
methodForRequest: ({ requestType }) => {
console.log('Log')
if (requestType === "updateRecord") {
return "PUT";
}
return this._super(...arguments);
},
pathForType(type) {
return camelize(type) + 's';
},
headers: computed(function () {
if (!App.StoreUtil.getSessionId()) {
if (App.GPT.ApplicationController) {
App.GPT.ApplicationController.set("hasMessages", [
{
message: "Session expired."
}
]);
App.GPT.ApplicationController.transitionToRoute("/");
} else {
window.location = "/";
}
}
return {
sid: App.StoreUtil.getSessionId()
};
}).volatile()
});
The code added to convert the request to PUT is :
methodForRequest: ({ requestType }) => {
console.log('Log')
if (requestType === "updateRecord") {
return "PUT";
}
return this._super(...arguments);
}
However, the method is not called at all. The funny part is pathForType is called for every request.
methodForRequest will only be available if you are using ember-data 2.8+ and you have the ds-improved-ajax flag enabled in environment.js
your other option is to override updateRecord()

Parse JS SDK: Cannot use the Master Key, it has not been provided

I need to use masterKey inside my angular2 app, but I can't pass it to initialize function and I can't google out why.
From package.json: "parse": "~1.9.2".
Initialization:
import {Parse} from '~/node_modules/parse/dist/parse';
#Injectable()
export class TFCloudService {
constructor() {
this.parse = Parse;
Parse.initialize(appConfig.parse.appId, null, appConfig.parse.masterKey);
Parse.serverURL = appConfig.parse.clientServerUrl;
Parse.liveQueryServerURL = appConfig.parse.liveQueryServerURL;
}
}
Error source:
this.edittedUser.save(null, {useMasterKey: true})
.then((user) => {
console.log(user);
});
Error text:
Error: Cannot use the Master Key, it has not been provided.
appConfig.parse.masterKey works fine, I checked that line with hard-coded key too, but got the same result.
Actually guessed the right way to pass that key:
Parse.initialize(appConfig.parse.appId);
Parse.masterKey = appConfig.parse.masterKey;

How to find a record both by id and query parameters in Ember

I'm trying to use ember-data to send a request via id and query parameters to an endpoint. The end output of the ajax call would be http://api.example.com/invoices/1?key=value. As far as I know, ember-data's store doesn't have a native way to find by both id and query parameters (neither of the following worked):
// outputs http://api.example/com/invoices/1
this.store.find('invoice', 1);
// outputs http://api.example.com/invoices?id=1&key=value
this.store.find('invoice, {id: 1, key: value});
Instead, I've been attempting to modify the invoice adapter. Our backend is Django, so we're using the ActiveModelAdapter. I want to override the method that builds the url so that if id is present in the query object, it will automatically remove it and append it to the url instead before turning the rest of the query object into url parameters.
The only problem is that I can't figure out which method to override. I've looked at the docs for ActiveModelAdapter here, and I've tried overriding the findRecord, buildUrl, urlForFind, and urlForQuery methods, but none of them are getting called for some reason (I've tried logging via console.log and Ember.debug). I know the adapter is working correctly because the namespace is working.
Here's my adapter file:
import DS from 'ember-data';
import config from '../config/environment';
export default DS.ActiveModelAdapter.extend({
namespace: 'v1',
host: config.apiUrl,
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
urlForFindRecord: function(id, modelName, snapshot) {
Ember.debug('urlForFindRecord is being called');
if (this.urlForFind !== urlForFind) {
Ember.deprecate('BuildURLMixin#urlForFind has been deprecated and renamed to `urlForFindRecord`.');
return this.urlForFind(id, modelName, snapshot);
}
return this._buildURL(modelName, id);
},
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
findRecord: function(store, type, id, snapshot) {
Ember.debug('findRecord is being called');
var find = RestAdapter.prototype.find;
if (find !== this.find) {
Ember.deprecate('RestAdapter#find has been deprecated and renamed to `findRecord`.');
return this.find(store, type, id, snapshot);
}
return this.ajax(this.buildURL(type.modelName, id, snapshot, 'findRecord'), 'GET');
},
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
urlForQuery: function(query, modelName) {
Ember.debug('urlForQuery is being called');
if (this.urlForFindQuery !== urlForFindQuery) {
Ember.deprecate('BuildURLMixin#urlForFindQuery has been deprecated and renamed to `urlForQuery`.');
return this.urlForFindQuery(query, modelName);
}
return this._buildURL(modelName);
},
// taken straight from the build-url-mixin and modified
// very slightly to test for logging
_buildURL: function(modelName, id) {
Ember.debug('_buildURL is being called');
var url = [];
var host = get(this, 'host');
var prefix = this.urlPrefix();
var path;
if (modelName) {
path = this.pathForType(modelName);
if (path) { url.push(path); }
}
if (id) { url.push(encodeURIComponent(id)); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url && url.charAt(0) !== '/') {
url = '/' + url;
}
return url;
},
});
Is there an easier way to accomplish what I'm trying to do without overriding adapter methods? And if not, what method(s) do I need to override?
Thanks in advance for your help!
You can use this.store.findQueryOne('invoice', 1, { key: value });
https://github.com/emberjs/data/pull/2584

Categories

Resources