I have a contact model that uses maps but the return is null thus causing aysnc suspension. I have tried tried setting these maps to return an empty list but to no avail do I manage to resolve the issue.
ContactModel{
//factory method constructor
emails: List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))),
tasks: List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))),
notes: List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))),
}
The error returns as : No such method map called on null. Receiver null
I have tried to resolve the issue by writing it as such
ContactModel{
//factory method constructor
emails: List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))).toList() ?? [],
tasks: List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))).toList() ?? [],
notes: List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))).toList() ?? [],
}
You can try null checking the json like so :
ContactModel{
emails: parsedJson['Emails'] != null ? List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x))).toList() : [],
tasks: parsedJson['Tasks'] != null ? List<Tasks>.from(parsedJson["Tasks"].map((x) => Tasks.fromJson(x))).toList() : [],
notes:parsedJson['Notes'] != null ? List<Notes>.from(parsedJson["Notes"].map((x) => Notes.fromJson(x))).toList() : [],
}
Basically, I always check 2 things when working with JSON types :
You must check your JSON contains the key you're looking for
You must check null value being returned if the key exist.
I recommend you doing this double check like this :
if(parsedJson.isNotEmpty) {
List<dynamic> emails = [];
if (parsedJson.containsKey('Email') && parsedJson['Email'] is List) {
emails = List<Email>.from(parsedJson['Emails'].map((x)=>Email.fromJson(x)))
}
ContactModel({emails: emails});
}
This way, you always make sure you've got the right type, and avoid production error (imagine your API going nuts). It's more verbose, I know, but to me, good code requires accuracy
Related
Given this query here,
let output = [];
const sql = `select * from coredb.account LIMIT ${offset},${limit}`;
let data = await sequelize.query(sql, null, {raw: true, type: sequelize.QueryTypes.SELECT});
data.forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
the data variable is indeed hydrated with the right row data when using console.log to inspect it.
But, when I try to access the individual properties, they only ever come back as undefined. This TextRow object that Sequelize seems to return the result in doesn't seem to want to let me access then explicit rows.
Just curious what i'm missing here, am I missing an option?
I agree, Sequalize raw queries are not intuitive. You don't need the null or raw: true flag. Something like this should work:
let data = await sequelize.query(sql, {type: sequelize.QueryTypes.SELECT});
When I tried this, "data" was an array of two objects, each being the query result. So, the properties can be accessed by using index [0].... e.g.
data[0].forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
Not yet sure WHY this occurs!
EDIT - it's because .query() should have only two arguments. Changing the call to: sequelize.query(sql, {raw: true, type: sequelize.QueryTypes.SELECT}) resulted in data being a single array (as expected).
Finally I was able to find the solution for it.
You just need to make a new array and push data into it by finding bases on key name like this:
suppose we have data in students object:
let finalArray = new Array();
for (var k in students ) {
finalArray.push(students[k])
}
console.log(finalArray) // Normal JSON array object :)
m.sequelize.query(sql, {
model,
mapToModel: true
})
.then(model => res.status(200).send(model))
.catch(error => res.status(400).send(error.toString())
})
I am trying to add a new key-value pair to the already loaded JSON Array. I am adding the new key-value pair to customize the header column cells in react bootstrap table but getting the below errors. Can any one please help?
'Columns' in the below state is where I wanted to add new key-value pair
state = {
data: MYResult.Products || [],
actualData: MYResult.Products || [],
columns: MYResult.ParametricList_Attributes || [],
isCompareClicked: false,
isDisabled: true,
selected: []
};
This is how I am adding the key-value pair -
componentDidMount(){
checkbox = (column, colIndex) => {
return (
<h5>{ column.text }<checkbox/></h5>
);
}
console.log(this.state.columns) ;
newColumn = this.state.columns.map((column) => {
return {...column, headerFormatter: checkbox};
});
this.setState({columns: newColumn });
}
Full code here - https://codesandbox.io/s/o1r988qkz Please uncomment the componentDidMount() to see the issue
Firstly, there's a typo in dcolumn and column.
And regarding the not defined error, you need to define it using const. Use like:
const checkbox = (column, colIndex) => {
return (
<h5>{column.text}<checkbox /></h5>
);
}
JavaScript variables need to be declared when they are used. Public class syntax can not be used everywhere. The error you're getting is self-evident - 'checkbox is not defined'.
Refer this on how to use it: https://tylermcginnis.com/javascript-private-and-public-class-fields/
I simply declared the undeclared variables in your example and the code worked.
Trying to create a new jira ticket of specific requestType, but it is nested two levels deep. Tried few possible alterations, but no luck. Here's the code I have,
require 'jira-ruby' # https://github.com/sumoheavy/jira-ruby
options = {
:username => jira_username,
:password => jira_password,
:site => 'https://jiraurl/rest/api/2/',
:context_path => '',
:auth_type => :basic,
:read_timeout => 120
}
client = JIRA::Client.new(options)
issue = client.Issue.build
fields_options = {
"fields" =>
{
"summary" => "Test ticket creation",
"description" => "Ticket created from Ruby",
"project" => {"key" => "AwesomeProject"},
"issuetype" => {"name" => "Task"},
"priority" => {"name" => "P1"},
"customfield_23070" =>
{
"requestType" => {
"name" => "Awesome Request Type"
}
}
}
}
issue.save(fields_options)
"errors"=>{"customfield_23070"=>"Operation value must be a string"}
Also tried passing a JSON object to customfield_23070,
"customfield_23070": { "requestType": { "name": "Awesome Request Type" } }
still no luck, get the same error message.
If it helps, this is how customfield_23070 looks like in our Jira,
Does anyone know how to set requestType in this case, please? Any help is greatly appreciated!!
It seems that for custom fields with specific data types (string/number), you must pass the value as:
"customfield_1111": 1
or:
"customfield_1111": "string"
instead of:
"customfield_1111":{ "value": 1 }
or:
"customfield_1111":{ "value": "string" }
I'm not sure but you can try this possible examples:
eg.1:
"customfield_23070"=>{"name"=>"requestType","value"=>"Awesome Request Type"}
eg.2:
"customfield_23070"=>{"requestType"=>"Awesome Request Type"}
eg.3:
"customfield_23070"=>{"value"=>"Awesome Request Type"}
eg.4
"customfield_23070"=>{"name"=>"Awesome Request Type"}
for ref there are 2 methods depending upon the fields you are interacting with
have a look here '
updating-an-issue-via-the-jira-rest-apis-6848604
' for the applicable fields for update via verb operations, the other fields you can use examples as per above,
you can use both methods within the same call
{
"update": {"description": [{"set": "Description by API Update - lets do this thing"}]},
"fields": {"customfield_23310": "TESTING0909"}
}
Ok, I think I found how to do it.
You need to provide a string, and that string is the GUID of the RequestType.
In order to get that GUID. You need to run the following in a scriptrunner console:
import com.atlassian.jira.component.ComponentAccessor
def issue = ComponentAccessor.issueManager.getIssueByCurrentKey("ISSUE-400546") //Issue with the desired Request Type
def cf = ComponentAccessor.customFieldManager.getCustomFieldObjectByName("Tipo de solicitud del cliente") //Change it to the name of your request type field
issue.getCustomFieldValue(cf)
Source: https://community.atlassian.com/t5/Jira-Software-questions/how-to-set-request-type-value-in-while-create-jira-issue/qaq-p/1106696
I've have API test
public function loginAsRegisteredUser(\ApiTester $I)
{
$I->wantTo('Login as registered user');
$I->sendPOST('/action.php?ap=V4&p=Customer&c=Customer&a=login',['customer' => ['email' => $this->registered_user_email, 'password' => $this->registered_user_password]]);
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK); // 200
$I->seeResponseIsJson();
$I->seeResponseMatchesJsonType(["customer" => ["id_customer"=> 'string|null',"first_name"=>'string|null',"last_name"=>'string|null',"newsletter"=>'string|null']]);
}
and id_customer field always fails comparation
1) LoginCest: Login as registered user
Test tests/api/LoginCest.php:loginAsRegisteredUser
Step See response matches json type {"customer":{"id_customer":"string|null","first_name":"string|null","last_name":"string|null","newsletter":"string|null"}}
Fail `id_customer: 1` is of type `string|null`
Example of response:
{"customer":{"id_customer":1,"first_name":"as","last_name":"ewq","newsletter":"1"}}
I've tried all possible types for field id_customer(number for example), but no one works. Does anyone now solution?
It actually is validating correctly - your expectations are wrong.
Expected type is string or null, but the actual type is integer.
Supposing I have this return value
return JsonResponse( { 'message' : 'success', 'id' : newProductType.id }, safe = False )
and I have this function on success
.then( function( rs ){
alert(rs.id)
Problem is, it alerts an undefined value. How do I access the id field in that object? Sorry, maybe its a very simple problem but Im a newbie so bear with me.
You can use
rs.new_id
Because your response haven't id field.