Is it possible to raise multiple errors in Errors[] array, like hotchocolate does when you try to use unknow properties ?
If yes, how can I do this ?
My use case is to return errors collection when validating an object with Validator.TryValidateObject
See below what hotchocolate returns when fields are unknow.
I would like to do the same : multiple elements in Errors[] array.
{
"Label": null,
"Path": null,
"Data": null,
"Errors": [
{
"Message": "The field `date` does not exist on the type `EcritureConnection`.",
"Code": null,
"Path": {
"Parent": null,
"Depth": 0,
"Name": "ecritures"
},
"Locations": [
{
"Line": 1,
"Column": 75
}
],
"Extensions": {
"type": "EcritureConnection",
"field": "date",
"responseName": "date",
"specifiedBy": "http://spec.graphql.org/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types"
},
"Exception": null
},
{
"Message": "The field `intitule` does not exist on the type `EcritureConnection`.",
"Code": null,
"Path": {
"Parent": null,
"Depth": 0,
"Name": "ecritures"
},
"Locations": [
{
"Line": 1,
"Column": 80
}
],
"Extensions": {
"type": "EcritureConnection",
"field": "intitule",
"responseName": "intitule",
"specifiedBy": "http://spec.graphql.org/June2018/#sec-Field-Selections-on-Objects-Interfaces-and-Unions-Types"
},
"Exception": null
}
],
"Extensions": null,
"ContextData": {
"HotChocolate.Execution.ValidationErrors": true
},
"HasNext": null
}
There are multiple ways of setting errors in HotChocolate
How to build errors
Both ways require you to create a IError object.
You can use the ErrorBuilder to build this error. You do not need to set all of the fields, but the more the better the error does look:
ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.SetException(ex)
.AddLocation(context.Selection.SyntaxNode)
.SetPath(context.Path)
.Build()
This would generate this error in the response:
{
"errors": [
{
"message": "This is the message",
"locations": [
{
"line": 3,
"column": 21
}
],
"path": [
"hello"
],
"extensions": {
"code": "YOURCODE00000123"
}
}
],
"data": {
"hello": "World"
}
}
How to raise errors
You can report errors on the IResolverContext or the IMiddlewareContext
Annotation Based
public class Query
{
public string Hello(IResolverContext context)
{
context.ReportError(
ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.AddLocation(context.Selection.SyntaxNode)
.SetPath(context.Path)
.Build());
return "World";
}
}
Code First
public class QueryType : ObjectType<Query>
{
protected override void Configure(IObjectTypeDescriptor<Query> descriptor)
{
descriptor.Field(x => x.Hello)
.Resolver(context =>
{
context.ReportError(
ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.AddLocation(context.Selection.SyntaxNode)
.SetPath(context.Path)
.Build());
return "World";
});
}
}
By throwing a GraphQlException
public class Query
{
public string Hello()
{
var error1 = ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.Build();
var error2 = ErrorBuilder.New()
.SetMessage("This is the message")
.SetCode("YOURCODE00000123")
.Build();
throw new GraphQLException(error1, error2)
}
}
Related
I have 2 JSON Data 1. Payers 2. Rules. I need to filter Payers JSON data based on PayerId from Rules JSON data.
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}}
Rules JSON file
{
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
}]}
I need to filter Payers JSON data based on Rules JSON data if PayerID matches
I need output like below
{
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "34567",
"name": "Test Payer3"
}
}
How to filter?
You can use Array.filter like that (based on your data structure):
const filteredPayers = payersObj.Payers.filter((p) => rulesObj.Rules[0].Criteria[0].payerId.includes(p.payerId));
I can't figure out why your Rules json looks like this, I guess you have multiple rules. If so, you will need to iterate over each rule and invoke includes. Same for Criteria.
Code will check each rule and each critirias
and will return payers if payerId found in any of the given rules of any criteria
const payers = {
"Payers": [
{
"payerId": "12345",
"name": "Test Payer1"
},
{
"payerId": "23456",
"name": "Test Payer2",
},
{
"payerId": "34567",
"name": "Test Payer3"
}]}
const rules = {
"Rules": [
{
"actions": {
"canCopyRule": true
},
"RuleId": 123,
"description": "Test Rule",
"isDisabled": false,
"Criteria": [
{
"autoSecondaryCriteriaId": 8888,
"criteriaType": { "code": "primaryPayer", "value": "Primary Payer" },
"payerId": ["12345", "34567"]
}
]
}
]
}
const data = payers.Payers.filter(payer => rules.Rules.findIndex(rule => rule.Criteria.findIndex(criteria => criteria.payerId.includes(payer.payerId)) != -1) !== -1)
console.log(data)
I am working in fauna DB. I have a confusion for writing an query to update a field . From the given array object I want to update the Boolean fields ( "presentation", "keyTakeaways", "whitepaper", "downloadAll") with the reference to the SegmentAnonymousID. I am adding the code that I tried. Can someone help me to sort out the problem.
[{
"ref": Ref(Collection("Downloads"), "322568726157197900"),
"ts": 1643884359510000,
"data": {
"SegmentAnonymousID": "57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a",
"response": {
"firstname": "test ",
"lastname": "test 1",
"email": "test#gmail.com",
"company": "test",
"presentation": false,
"keyTakeaways": false,
"whitepaper": false,
"downloadAll": false
}
}
},
{
"ref": Ref(Collection("Downloads"), "322484599970071113"),
"ts": 1643870069845000,
"data": {
"SegmentAnonymousID": "15ba9e0d-e646-4d31-beaa-b2a4d3eac56f",
"response": {
"firstname": "test 4",
"lastname": "test4",
"email": "test#gmail.com",
"company": "test",
"presentation": false,
"keyTakeaways": false,
"whitepaper": false,
"downloadAll": false
}
}
}]
The code I tried
const result = await faunaClient.query(
q.Update(
q.Select("ref", q.Get(q.Match(q.Index("SegmentAnonymousID"), "57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a")), { data: { response: { "presentation": true } } })
)
)
Your query has brackets in the wrong place. As written, the object containing the new data appears as the "default" value for the Select call. You'll likely have better success with this update (reformatted to show function calls and parameters better):
const result = await faunaClient.query(
q.Update(
q.Select(
"ref",
q.Get(
q.Match(
q.Index("SegmentAnonymousID"),
"57f22fc0-2ace-4522-b0a6-4d0cd45cfc3a"
)
)
),
{
data: {
response: {
presentation: true
}
}
}
)
)
Here is my json respond using laravel spatie I created a respond that show if the user is have an Roles
{
"message": "Successfuly fetch all User",
"error": false,
"error_code": 200,
"line": "line 117 UserController.php",
"data": [
{
"id": 1,
"name": "dasdsa",
"email": "dasdsad#gmail.com",
"email_verified_at": null,
"created_at": "2020-04-22T13:37:41.000000Z",
"updated_at": "2020-04-22T13:37:41.000000Z",
"roles": [
{
"id": 2,
"name": "publisher",
"guard_name": "web",
"created_at": "2020-04-23T11:11:33.000000Z",
"updated_at": "2020-04-23T11:11:33.000000Z",
"pivot": {
"model_id": 1,
"role_id": 2,
"model_type": "App\\User"
}
}
]
},
{
"id": 2,
"name": "mdsadsadn",
"email": "dasdsad#gmail.coms",
"email_verified_at": null,
"created_at": "2020-04-23T10:37:10.000000Z",
"updated_at": "2020-04-23T12:04:46.000000Z",
"roles": [
{
"id": 2,
"name": "publisher",
"guard_name": "web",
"created_at": "2020-04-23T11:11:33.000000Z",
"updated_at": "2020-04-23T11:11:33.000000Z",
"pivot": {
"model_id": 2,
"role_id": 2,
"model_type": "App\\User"
}
}
]
}
]
}
and this is my code on angular 9.1.3 to get the value name in roles array
export class UserComponent implements OnInit {
roles:any;
result:any;
constructor(private _userService:UsersService) { }
ngOnInit(): void {
this.getallUser();
}
getallUser(){
this._userService.getallUsers().subscribe((event : HttpEvent<any>) => {
if (event.type === HttpEventType.Response) {
if (event.status == 200) {
let body = event.body;
let error = body.error;
let msg = body.message;
//alert(body);
// console.log(body.data);
if (!error) {
this.dataTbl.tblVal = body.data
this.roles = body.data.roles;
console.log(this.roles)
// this.result = this.roles.map(a => a.roles);
// console.log(this.result);
// console.log(this.dataTbl.tblVal)
}
}
}
this.dataTbl.tblLoad = false;
}, (err : HttpErrorResponse) => {
console.log(err);
});
}
}
Here is my service
import { Injectable } from '#angular/core';
import { HttpClient, HttpRequest, HttpHeaders } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private _httpClient: HttpClient) {
}
getallUsers() {
return this._httpClient.get("http://localhost:8000/api/getallUser", {
observe: 'response', reportProgress: true });
}
}
My problem is I want to get the value of name in roles example:publisher but i cannot access on that object how to get that value the error is undefined I dont know what's wrong with my code thank you for the help
I am trying to parse this JSON using Powershell's ConvertFrom-Json feature, but it seems to truncate the data:
{
"MessagesMonitoring": {
"version": 1,
"description": "Message Description"
},
"data": {
"swindon": {
"totalMessages": 0,
"identifier": [
{
"name": "ET",
"staleCount": 4
},
{
"name": "ET_2",
"staleCount": 4
}
]
},
"Reading": {
"totalMessages": 0,
"identifier": [
{
"name": "J3",
"staleCount": 2
}
]
},
"Yanki": {
"totalMessages": 0,
"identifier": [
{
"name": "UT",
"staleCount": 4
},
{
"name": "UT_2",
"staleCount": 4
}
]
}
}
}
Request:
$request = 'http://localhost:8000/hi.json'
Invoke-WebRequest $request |
ConvertFrom-Json |
Select swindon
Response:
StatusCode : 200 StatusDescription : OK
Content : {
"MessagesMonitoring": {
"version": 1,
"description": "Message Description"
},
"data": {
"swindon": {
"totalMessages": 0,
"identifier": [
{
"na...
Not sure what I may be doing incorrectly. Any advise/guidance on how to parse the JSON into this format would be great.
swindon|identifier|ET|4
swindon|totalMessages|0
swindon|identifier|ET2|4
Reading|identifier|J3|2
Reading|totalMessages|0
Yanki|identifier|UT|4
Yanki|identifier|U_T|4
Yanki|totalMessages|0
You are missing a step. The Content element of the response contains the JSON, so that's what you need to feed into ConvertFrom-Json:
$request = 'http://localhost:8000/hi.json'
$resp = $(Invoke-WebRequest $request).Content | ConvertFrom-Json
Then, within the JSON you have a dictionary, within which the "data" key contains the information I think you're interested in, access it using this syntax:
$resp.data
That should get you started
Below is my returned json from twitter
{
"created_at": "Sat, 11 Feb 2012 06:38:28 +0000",
"entities": {
"hashtags": [
{
"text": "Shubhdin",
"indices": [
9,
18
]
}
],
"urls": [],
"user_mentions": [
{
"screen_name": "SAMdLaw",
"name": "Sabyasachi Mohapatra",
"id": 104420398,
"id_str": "104420398",
"indices": [
0,
8
]
}
]
},
"from_user": "nilayshah80",
"from_user_id": 213599118,
"from_user_id_str": "213599118",
"from_user_name": "Nilay Shah",
"geo": {
"coordinates": [
18.6003,
73.825
],
"type": "Point"
},
"id": 168222351106899968,
"id_str": "168222351106899968",
"iso_language_code": "in",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"source": "<a href="http://twabbit.wordpress.com/" rel="nofollow">twabbit</a>",
"text": "#SAMdLaw #Shubhdin mitra",
"to_user": "SAMdLaw",
"to_user_id": 104420398,
"to_user_id_str": "104420398",
"to_user_name": "Sabyasachi Mohapatra",
"in_reply_to_status_id": 168219865197461505,
"in_reply_to_status_id_str": "168219865197461505"
},
{
"created_at": "Sun, 12 Feb 2012 01:54:07 +0000",
"entities": {
"hashtags": [
{
"text": "IWIllAlwaysLoveYou",
"indices": [
88,
107
]
}
],
"urls": [],
"user_mentions": [],
"media": [
{
"id": 168513175187238912,
"id_str": "168513175187238912",
"indices": [
108,
128
],
"media_url": "http://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"media_url_https": "https://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"url": "http://shortener.twitter.com/dRc4dXH3",
"display_url": "pic.twitter.com/dRc4dXH3",
"expanded_url": "http://twitter.com/RIPWhitneyH/status/168513175183044608/photo/1",
"type": "photo",
"sizes": {
"orig": {
"w": 395,
"h": 594,
"resize": "fit"
},
"large": {
"w": 395,
"h": 594,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 340,
"h": 511,
"resize": "fit"
},
"medium": {
"w": 395,
"h": 594,
"resize": "fit"
}
}
}
]
},
"from_user": "RIPWhitneyH",
"from_user_id": 19319043,
"from_user_id_str": "19319043",
"from_user_name": "RIP Whitney Houston",
"geo": null,
"id": 168513175183044608,
"id_str": "168513175183044608",
"iso_language_code": "en",
"metadata": {
"recent_retweets": 8,
"result_type": "popular"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"source": "<a href="http://twitter.com/">web</a>",
"text": "R-T if you think that the Grammy's should organize an \"R.I.P. Whitney Houston\" tribute. #IWIllAlwaysLoveYou http://shortener.twitter.com/dRc4dXH3",
"to_user": null,
"to_user_id": null,
"to_user_id_str": null,
"to_user_name": null
},
If you noticed Media under entities not available in above 2 and when i tried to call below snippet gives me null reference error
MediaUrl = (from user in tweet["entities"]["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
Same code work for Entities/URL, Hashtags and mentions but not for Media.
Also tried this -> Get JSON object node but still getting null reference exception.
In first tweet, entities object doesn't have media property, so when evaluating first tweet, your code would be equivalent to :
MediaUrl = (from user in (IEnumerable<JToken>)null
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
which will throw ArgumentNullException because that code does query on null reference collection.
Finally got working. Not appropriate solution but works for me.
I created separate method for parsing Media. Passed Entity as string and in that method i checked is EntityString.Contains Media or not. If yes, then parse media json else returned null. See below Snippet.
if (Entities != string.Empty)
{
if (Entities.Contains("\"media\":"))
{
JObject searchResult = JObject.Parse(Entities);
returnMedia = (from user in searchResult["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList();
}
}
This works for me. If you have any better solution then Please let me know.