json string casting issue - dart

data[i]['title']=
{varent_pos: 1, varent_ct: 0, title: Aashirvaad Atta with Multigrains
pouch, imageslist: [], varent_id: null, id: 43469930505}
try {
final parsed = json.decode(data[i]['title']);
} on FormatException catch (e) {
print("That string didn't look like Json.");
} on NoSuchMethodError catch (e) {
print('That string was null!');
}"
But it is showing "That string didn't look like Json"
print(data[i]['title']);
{varent_pos: 1, varent_ct: 0, title: Aashirvaad Atta with Multigrains
pouch, imageslist: [], varent_id: null, id: 43469930505}

First try printing the content of data[i]['title'] just to make sure it's a String and seems valid.
After that you can try running the JSON through https://jsonlint.com/ that linter.
And last but not list try printing the actual exception in the catch statement, maybe it carries more information that could be useful.

Related

How to debug Flutter Amplify Graphql requests?

I'm trying to return a list of my model sorted by date. But I run into a vague error.
Here is my graphql.schema
type Vote #model(timestamps: { createdAt: "created_at", updatedAt: "updated_at" }) {
id: ID!
name: String!
date: AWSTimestamp #index(name: "date-index", sortKeyFields: ["name"], queryField: "getVotesByDate")
}
Here is the request:
Future<List<Vote?>> recentVotes() async {
const getRecentVotes = "getRecentVotes";
String document = """
query getRecentVotes {
listVotes(limit: 5) {
items {
date
id
name
}
nextToken
}
}
""";
try {
final request = GraphQLRequest(
document: document,
modelType: Vote.classType,
decodePath: getRecentVotes,
);
final response = await Amplify.API.query(request: request).response;
List<Vote?>? votes = response.data?.items;
if (votes == null) {
return [];
}
_voteLength = votes.length;
return votes;
} catch (err) {
debugPrint(err.toString());
}
return [];
}
The error I get back is pretty terrible:
flutter: ApiException(message: The HTTP response status code is [400]., recoverySuggestion: The metadata associated with the response is contained in the HTTPURLResponse.
flutter: For more information on HTTP status codes, take a look at
flutter: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes, underlyingException: null)
As best I can tell, it's just a standard bad request error but with no message of what makes it bad. The graphql syntax is valid and tested.
*Edit
I've managed to restart the app which provided more details about the error. With the same code, I now get
flutter: type 'Null' is not a subtype of type 'String'
My first thought after this is that there's some returned field that is null that cannot be. I've checked the name and the id of all the records in the database and they are not null so I'm not sure how that's possible.

Twilio Studio - How To Access Array Items From JSON Output of Function

I'm calling the function below in Twilio Studio from a run function widget, then saving the EmployeeInfo to a variable setting the EmployeeInfo variable to value {{widgets.function_1.parsed.EmployeeInfo}} . When I put the code {{flow.variables.EmployeeInfo}} into a say/play widget it will say all of the data elements but I'm having trouble accessing a single value (like saying a single Name). I tried every conceivable syntax I could think of such as {{flow.variables.EmployeeInfo[0].Name}} and {{flow.variables.EmployeeInfo.Name[0]}} but nothing will play. Do I have some syntax error somewhere, or maybe are you not able to store arrays in variables?
exports.handler = function(context, event, callback) {
let results = {
LastName: "WAYNE",
FirstName: "BRUCE",
EmployeeInfo: [{ ID: 1, Name:"test" }, { ID: 2, Name:"tested" }, { ID: 3, Name:"testing" }]
};
return callback(null, results);
};
I am just learning twilio studio flows as well and found that the systax is "{{widgets..parsed.EmployeeInfo[0].Name}}"

Can't place GraphQL custom type as a Postman variable

Has anyone had luck with placing a GraphQL custom type argument as a Postman or Graphql variable? I'm kinda spinning in circles right now, I hope a fresh pair of eyes could point me in the right direction.
What I'm trying to do is to send a mutation request using Postman. The problem I'm having is that the method I'm calling is taking a custom type as an argument. Placing the content of that variable as GraphQL variable or Postman variable is giving me a headache. I can't embedd pictures yet, so here are the links (they are safe).
Schema
This custom type is a JSON-like structure, consisting of two enums and a set of primitive types (strings, ints...). I can screenshot the entire thing but basically that's it: two enums followed by strings, ints...
Custom type definition
What I've tried so far:
Simply hardcoding the request in Postman works but I wish to send multiple requests with varying data
Placing it in a GraphQL variable results in error message
{
"errors": [
{
"message": "Bad request - invalid request body.",
"locations": []
}
],
"data": null
}
Placing the custom type content as a Postman environment variable works, but I'm getting a syntax error (although the request passes...).
Request body is below. Hardcoding it and using a Postman variable produces the same request body, apart from the syntax error.
query: "mutation {
createApplication(request: {
applicationKind: NEW_ISSUANCE,
documentKind: REGULAR_PASSPORT,
personalData: {
timestamp: null,
firstname: "NAME",
lastname: "LASTNAME",
middlename: "MIDDLENAME",
dateOfBirth: "2011-09-28",
citizenshipCountryCode: "USA",
gender: MALE,
personalNumber: "3344",
placeOfBirth: "CHICAGO",
municipalityOfBirth: "SOUTH",
countryCodeOfBirth: "USA"},
addressData:{
street: "WEST",
municipality: "EAST",
place: "CHICAGO",
country: {
code: "USA",
name: null
},
entrance: "б",
flat: "13",
number: "35"}
})
{
__typename
... on AsyncTaskStatus {
taskID
state
payload {
... on ApplicationUpdated {
applicationID
applicationNumber
__typename
}
__typename
}
__typename
}
... on Error {
...errorData
__typename
}
}
}
fragment errorData on Error {
__typename
code
message
}"
Postman variable with a squiggly line
I'm spinning in circles right now. Has anyone had any luck with Postman requests of this kind?
I can post more info, screenshots...just let me know. I'll be watching this topic closely and provide feedback.
Thank you for your time.
please add a the variable in variable section as :
{
"request": {{request}}
}
and then refer this in your query as
$request

Apollo server, GraphQL and Sequelize - how to put raw data into a GraphQL Schema Response

After scouring the internet for a specific example, I am throwing in the towel and asking for some help.
I am using Apollo server, GraphQL and Sequelize, and I am calling stored procedure that returns a record set created from two different tables. I am getting the data back, but I cannot figure out how to put the result into a GraphQL schema response.
Here is the code in my resolver:
async functionName(_, {input}, {user = null}) {
if (!user) {
throw new AuthenticationError('You must login to use this function');
}
const {record_id} = input;
const result = await DBService.query(
'Call sp_JoinTwoTables_Select(:id)',
{
model: FooModel,
mapToModel: true,
raw: true,
replacements: {id: record_id},
type: QueryTypes.SELECT
}
);
console.log('functionName.result');
console.log(result); // Getting results
return result;
}
Here is the code in my schema:
const {gql} = require('apollo-server-express');
module.exports = gql`
type Foo {
id: Int!
foo_name: String!
date_created: String!
date_modified: String!
}
extend type Mutation {
functionName(input: fooInput!): fooResponse!
}
input fooInput {
id: Int!
}
type fooResponse {
tree: [fooSchemaForBothTables!]
}
type fooSchemaForBothTables {
id: Int!
foo_name: String!
column_from_second_table: Int!
}
`;
Since there is no table in the database, I created a simple object. When that failed I tried a sequelized model object, but that also is failing. Here is this code:
module.exports = {FooModel: {
id: 0,
fooName: '',
column_from_second_table: 0
}};
The output I am getting is (not a 2d array as I thought):
Executing (default): Call sp_CommunityHierarchy_Select(9)
selectHierarchyTree.result
[
{
'0': {
community_id: 1,
community_name: 'Cars',
level_from_apex: null,
parent_id: null
},
'1': {
community_id: 8,
community_name: 'Chevy',
level_from_apex: 2,
parent_id: 1
},
'2': {
community_id: 9,
community_name: 'Suburban',
level_from_apex: 3,
parent_id: 8
},
meta: [ [ColumnDef], [ColumnDef], [ColumnDef], [ColumnDef] ]
},
{ affectedRows: 6, insertId: 0, warningStatus: 0 }
]
Your 'raw' DB result:
is an array;
1st element is an object with records/items encoded as index-named properties;
Your required mutation (why not a query type!?) response should tree: [fooSchemaForBothTables!] - object with tree named property (really required additional nesting level?) with an array of fooSchemaForBothTables-shaped objects as values:
{
tree: [
{
id: 1,
foo_name: 'Cars`,
column_from_second_table: 'whatever`,
},
{
id: 2,
foo_name: 'Chevy`,
column_from_second_table: 'whatever`,
}
]
}
Your job is to convert DB response into the required mutation result shape.
Hint: You can hardcode this DB result (some input const) in a side project (codesandbox) and write some conversion fn. When ready use it in this resolver.
You can also search for some more reliable sequelize (leave graphql alone for a moment) tutorials with 'more working' model mapping.
Next step?
If it is a tree then why not return this as a tree structure - nested nodes/types?

How to verify types from response?

I have to check json response if it contains needed types. What do I mean:
{
"success": {
"anonym_id": 11156,
"has_empty_profile": false,
"token": "4690e404-cfec-4918-b555-2f0d84675eee",
"twins": [],
"uid": 7380
}
}
So I have to check that "anonym_id" is int(not a specific number like here 11156, but just int), "has_empty_profile" is boolean, "token" is string etc.
How to do that with rest assured?
Best way to do this is
JsonPath js1 = new JsonPath(new File(
"Your Json I stored in a file"));
assertTrue(js1.get("success.findAll {anonym_id -> anonym_id=11156}.has_empty_profile") instanceof Boolean);
assertTrue(js1.get("success.findAll {anonym_id -> anonym_id=11156}.token") instanceof String);

Resources