Template literal - getting error from API - reactjs

So i have a method that searches for anime by name, API is graphQL.
Here's the important part of the query
const searchQuery = this.state.searchString;
var query = `query Search{
# the rest of the query omitted for brevity
media(type:ANIME, search: ${searchQuery} ){
# ...
}
`
I'm getting two types of errors in response, first is when search string consists of multiple words separated by spaces - "Syntax Error: Expected :, found )"
Second when i search for single word - "Field "media" argument "search" requires type String, found naruto."
What is the problem here?
You can see full code here - https://github.com/red4211/react-anime-search , app deployed to github pages, search API response goes to console - https://red4211.github.io/react-anime-search/

The issue is that given some query like "naruto", your current code results in the following text:
media(type:ANIME, search: naruto ) {
This is not valid syntax since String literals should be surrounded by double quotes (").
Don't use string interpolation to provide dynamic values to the query. These should always be expressed as variables and included as a separate object inside your request alongside query.
You need to define the variable as part of your operation, providing the appropriate type
var query = `query Search ($searchQuery: String!) {
then you can use the variable anywhere inside the operation:
media(type:ANIME, search: $searchQuery) {
Now just pass the variable value along with your request.
body: JSON.stringify({
query,
variables: {
searchQuery,
}
})
Note that the variable name is prefixed with a $ inside the GraphQL document, but outside of it, we don't do that.

media() looks like a function, so in that case the correct syntax would be:
media(type="ANIME", search=searchQuery)
or if the argument of media() is an object
media({type: "ANIME", search: searchQuery})
Also, you don't need to use ${} around searchQuery since searchQuery is already a string. The usage for that would be something like
`${searchString}` or `foo${searchString}bar`
using the `` around the ${} utility to represent a string and its variable inside the string literal.
Hope it helps!

Related

Reactjs convert input string to upper case

I'm creating an app in Reactjs using react-strap. I would like to convert an input field to upper case.
From googling, it looks like simply appending "toUpperCase()" to the field would work, but this doesn't appear as an option in Visual Studio code.
I had a similar issue with doing a replace all, but finally got that to work using "const" field:
// replace ":" with "-"
const phrase = item.macs;
const replaced = phrase.replace(/:/g, '-')
item.macs = replaced;
However, converting to a const field doesn't work for making the "toUpperCase()" available.
What should I do to turn this into a string so I can call the "toUpperCase()" function?
Edit: change references from "toUpper" to "toUpperCase". The problem is this is not available as a function.
For example of I do
'myString'.toUpperCase();
it works. But it I can't get it to bring that up in Visual Studio Code, and it's ignored if I code it anyway.
I believe you are looking after toUpperCase.
To make a string uppercase in javascript you can call .toUpperCase() method on it. For example
const foo = 'foo'
const fooUpper = foo.toUpperCase()
console.log(fooUpper) // expected result 'FOO'
I got around this problem by forcing the input item to be regarded as a string by prepending it with a '', like so:
item.macs = '' + item.macs;
item.macs = item.macs.replace(/:/g, '-');
item.macs = item.macs.toUpperCase();
After that, all the string functions were available.

Issue using Graphql in my react app. I just can't get the variable section to work [duplicate]

So i have a method that searches for anime by name, API is graphQL.
Here's the important part of the query
const searchQuery = this.state.searchString;
var query = `query Search{
# the rest of the query omitted for brevity
media(type:ANIME, search: ${searchQuery} ){
# ...
}
`
I'm getting two types of errors in response, first is when search string consists of multiple words separated by spaces - "Syntax Error: Expected :, found )"
Second when i search for single word - "Field "media" argument "search" requires type String, found naruto."
What is the problem here?
You can see full code here - https://github.com/red4211/react-anime-search , app deployed to github pages, search API response goes to console - https://red4211.github.io/react-anime-search/
The issue is that given some query like "naruto", your current code results in the following text:
media(type:ANIME, search: naruto ) {
This is not valid syntax since String literals should be surrounded by double quotes (").
Don't use string interpolation to provide dynamic values to the query. These should always be expressed as variables and included as a separate object inside your request alongside query.
You need to define the variable as part of your operation, providing the appropriate type
var query = `query Search ($searchQuery: String!) {
then you can use the variable anywhere inside the operation:
media(type:ANIME, search: $searchQuery) {
Now just pass the variable value along with your request.
body: JSON.stringify({
query,
variables: {
searchQuery,
}
})
Note that the variable name is prefixed with a $ inside the GraphQL document, but outside of it, we don't do that.
media() looks like a function, so in that case the correct syntax would be:
media(type="ANIME", search=searchQuery)
or if the argument of media() is an object
media({type: "ANIME", search: searchQuery})
Also, you don't need to use ${} around searchQuery since searchQuery is already a string. The usage for that would be something like
`${searchString}` or `foo${searchString}bar`
using the `` around the ${} utility to represent a string and its variable inside the string literal.
Hope it helps!

Gatling .sign issue

I am trying to build a Get request as follows and I would like CaseReference value to be populated via feeder .feed(CaseProviderSeq) but for some reason it's not picking CaseReference value and printing following for my println statement in .sign statement bellow
PATH KJ: /caseworkers/554355/jurisdictions/EMPLOYMENT/case-types/Manchester_Multiples/cases/$%7BCaseReference%7D/event-triggers/updateBulkAction_v2/token
My feeder CSV got following rows currently
1574761472170530
1574622770056940
so I am expecting this amended URL would be like
/caseworkers/554355/jurisdictions/EMPLOYMENT/case-types/Manchester_Multiples/cases/1574761472170530/event-triggers/updateBulkAction_v2/token
any idea what wrong I am doing here ??
.get(session => SaveEventUrl.replace(":case_reference","${CaseReference}").replaceAll("events", "") + s"event-triggers/${EventId}/token")
.header("ServiceAuthorization", s2sToken)
.header("Authorization", userToken)
.header("Content-Type","application/json")
.sign(new SignatureCalculator {
override def sign(request: Request): Unit = {
val path = request.getUri.getPath
println("PATH KJ: " + path)
request.getHeaders.add("uri", path)
}
})
This is not related to .sign, but your session attribute CaseReference not being interpreted. If you look closely you can see the braces %-encoded in $%7BCaseReference%7D.
Interpretation of the Gatling Expression Language strings happens only when a String is present when an Expression[Something] is needed1.
This bug you wrote is shown exactly in the warning in the documentation above.
I believe you can simply remove session => in your .get, so you are passing in a String rather than a Session => String2. That string will be implicitly converted to Expression[String]. That way Gatling will put the session attribute into the URL.
This happens because of the Scala implicit conversion.
In fact it is Session => Validation[String], because, again, of implicit conversions.

How to set a context variable with dot in name?

I am trying to add a context data variable (CDV), which has a dot in its name. According to Adobe site this is correct:
s.contextData['myco.rsid'] = 'value'
Unfortunately, after calling s.t() the variable is split into two or more:
Context Variables
myco.:
rsid: value
.myco:
How can I set the variable and prevent splitting it into pieces?
You are setting it properly already. If you are referring to what you see in the request URL, that's how the Adobe library sends it. In your example, "myco" is a namespace, and "rsid" is a variable in that namespace. And you can have other variables in that namespace. For example if you have
s.contextData['myco.rsid1'] = 'value';
s.contextData['myco.rsid2'] = 'value';
You would see in the AA request URL (just showing the relevant part):
c.&myco.&rsid1=value&rsid2=value&.myco&.c
I assume you are asking because you want to more easily parse/qa AA collection request URLs from the browser network tab, extension, or some unit tester? There is no way to force AA to not behave like this when using dot syntax (namespaces) in your variables.
But, there isn't anything particularly special about using namespaces for your contextData variables; it's just there for your own organization if you choose. So if you want all variables to be "top level" and show full names in the request URL, then do not use dot syntax.
If you want to still have some measure of organization/hierarchy, I suggest you instead use an underscore _ :
s.contextData['myco_rsid1'] = 'value';
s.contextData['myco_rsid2'] = 'value';
Which will give you:
c.&myco_rsid1=value&myco_rsid2=value&.c
Side Note: You cannot do full object/dot notation syntax with s.contextData, e.g.
s.contextData = {
foo:'bar', // <--- this will properly parse
myco:{ // this will not properly parse
rsid:'value' //
} //
};
AA library does not parse this correctly; it just loops through top level properties of contextData when building the request URL. So if you do full object syntax like above, you will end up with:
c.&foo=bar&myco=%5Bobject%20Object%5D&&.c
foo would be okay, but you end up with just myco with "[object Object]" as the recorded value. Why Adobe didn't allow for full object syntax and just JSON.stringify(s.contextData) ? ¯\_(ツ)_/¯

proper way to get the last element of the array when split is used on the string within JSON

I have a JSON response from the server and I am using map to use only necessary key:valuepairs in Angular (typescript) that will be used to display on the Frontend side.
here bizStep is actually according to a standard (EPCIS) and has the following value:
urn:epcglobal:cbv:bizstep:receiving
I only want to the user to read receiving hence I used split and obtained the last value of the array to display the value.
The logic is shown below:
this.serv.getEpcisInfo(code) // HTTP GET Service from Angular
.subscribe(res => {
this.data = res.map(el => { // map only some key value pairs now!
return {
'business step': el.bizStep.split(':')[el.bizStep.split(':').length - 1]
});
});
But it is observed that in order to obtain the overall length of the splited string array I have to write the expression el.bizStep.split(':') twice.
Is there a shorthand or elegant expression to obtain the last string value of the array.
I did try to use el.bizStep.split(':')[-1] however this expression failed and did not provide me any value.
You can use Array.pop since you don't need to preserve the result of the split, i.e. el.bizStep.split(':').pop().
A more general approach would be to use an anonymous function, e.g.:
(s => s[s.length-1])(el.bizStep.split(':'))
You could modify this to get elements other than the last. Of course, this example has no error checking on the length or type of el.bizStep.

Resources