Return custom Error in Union Graphql Type while show list data | returning list with union type in graphql [duplicate] - express

This question already has answers here:
GraphQL Expected Iterable, but did not find one for field xxx.yyy
(10 answers)
Closed 2 years ago.
I'm using Apollo server for my project returning list(array) of data when I try to return Error union type it shows this error:
"errors": [
{
"message": "Expected Iterable, but did not find one for field \"Query.getReports\".",
My Schema:
type Query {
getReports(id: ID!, patient_id: Int): [getReportUnion]!
}
union getReportUnion = Error | getReportResult
type getReportResult {
id: ID!
patient_id: Int!
}
type Error {
error: Boolean!
message: String!
}
my Resolver:
getReports: async (parent: any, args: any, context: any, info: any) => {
/**
* Simplify
*/
const { id, patient_id } = args;
const { isAuth, userId } = context.Auth;
/**
* Authenticating user is logged in
*/
if (!!!isAuth || userId !== id)
return { __typename: "Error", error: err, message: mesg };
// if a user is logged in then it works well
}
and my query:
query {
getReports(id: "5f449b73e2ccbc43aa5204d88", patient_id: 0) {
__typename
... on getReportResult {
patient_id
date
}
... on Error {
error
message
}
}
}
The problem is when I tried to pass the wrong id argument or jwt token, it shows the error. if every id and jwt token as header are right then it works like charm. so question is when id or jwt token is wrong, I want to show the Error type to inform user something isn't alright!
I already tried but not working:
type Query {
getReports(id: ID!, patient_id: Int): getReportUnion!
}
union getReportUnion = Error | [getReportResult]
it shows another error, is there any workaround to get rid of this error and show the Error. your answer is valuable to us!

If your field's type is a List, then your resolver must return either an iterable (i.e. an array) or a Promise that resolves to one.
The type for your field is a List ([getReportUnion]). However, inside your resolver, you are returning an object literal:
return { __typename: "Error", error: err, message: mesg }
You should return an array instead:
return [{ __typename: "Error", error: err, message: mesg }]
There is no way for you to return either a List of getReportResult objects or a single Error object. The only way to do that would be to wrap getReportResult with another type and use that type inside your union instead.
type Query {
getReports(id: ID!, patient_id: Int): GetReportPayload!
}
union GetReportPayload = Error | GetReportResults
type GetReportResults {
results: [Report!]!
}
type Report {
id: ID!
patientId: Int!
}
type Error {
error: Boolean!
message: String!
}

Related

Graphql variable type error expecting unknown types "equals" and "in"

I am getting an error with Graphql type definition.
This is part of my query:
query MyQuery($myFirstVariable: NonEmptyString!, $mySecondVariable: [NonEmptyString!]!) {
myBooks(
input: {
filter: {
myFirstVariable: { equals: $myFirstVariable }
mySecondVariable: { in: $mySecondVariable }
}
// ...
}
) {
//...
}
Variables:
{
"myFirstVariable": "string",
"mySecondVariable": ["array of string"]
}
Errors:
"Variable "$myFirstVariable" of type "NonEmptyString!" used in position expecting type "equals!"
"Variable "$mySecondVariable" of type "[NonEmptyString!]!" used in position expecting type "in!"

Contract call returns error "Found input with 28 bits, expected 8". Polkadot.js and ink contracts

as the title suggest, Im trying to call PSP22 token contract and read balanceOf() function, but i get error that im passing a too big of a input (27 instead of 8)
Im trying to invoke balanceOf() PSP22 ink! contract.
When i initializing the token it works correctly and i can see the abi:
alanceOf: function createQuery(origin, options)
​​​​​
length: 2
​​​​​
meta: Object { isMutating: false, isPayable: false, identifier: "balance_of", … }
​​​​​​
args: Array [ {…} ]
​​​​​​​
0: Object { name: "owner", type: {…} }
​​​​​​​​
name: "owner"
​​​​​​​​
type: Object { info: 10, type: "AccountId" }
Here is the code:
const tokenContract = new ContractPromise(api, abiToken, "5FmJDyLBoYKfiaoPUcfR3WKh13HkwvXr2CYTNg5RLykNXY3A");
dispatch(set_token_contract(tokenContract));
const value = 0; // only useful on isPayable messages
// NOTE the apps UI specified these in mega units
const gasLimit = 3000n * 1000000n;
// (We perform the send from an account, here using Alice's address)
let alice = "5DaYseV9GSrGKrJYmKU5yymF9izPM2ZzG8f93xQK6hectHuo"
const { gasConsumed, result, output } = await tokenContract.query.balanceOf(alice, { gasLimit }alice);
here is the error:
RPC-CORE: call(callRequest: ContractCallRequest, at?: BlockHash): ContractExecResult:: createType(ContractExecResult):: Struct: failed on result: {"_enum":{"Ok":"ContractExecResultOk","Err":"ContractExecResultErr"}}:: Enum(Err):: Enum(Module):: Struct: failed on error: u8:: u8: Input too large. Found input with 28 bits, expected 8

chai throw with property deep equal

expect.to.throw returns a Proxy to the thrown Error, so I can use with.property in order to check some properties of the error.
I attach a details object on my custom errors but I can't test for them, since the with.property compares only using strict equals.
Can I compare this property using deep equal somehow?
Example:
class DocNotFoundError extends Error {
constructor(message, docId) {
super(message)
this.details = { docId }
}
}
const getDoc = id => {
throw new DocNotFoundError('errors.docNotFound', id)
}
const docNotFound = expect(() => getDoc('01234567890')).to.throw('DocNotFoundError')
docNotFound.with.property('details', { docId: '01234567890' }) // fails
The error will fail similar to
AssertionError: expected { Object (error, ...) } to have property 'details' of { Object (docId) }, but got { Object (docId) }
+ expected - actual
I assume this is due to it only checks for reference equality and not deep object equality.
First of all there is a typo in the question: DocNotFoundError should not be in quotes.
I managed to get it working with docNotFound.to.have.deep.property('details', { docId: '01234567890' }), so yes you should perform deep comparison to check if objects have keys with same values.
Source 1
Source 2

Create Connected object in GraphQL via Mutation

What is the best practice to create an object via mutation connected to another object.
Using the following schema:
type Question #model {
id: ID!
text: String!
answers: [Answer] #connection(name: "QuestionAnswers")
}
type Answer #model {
id: ID!
text: String!
question: Question #connection(name: "QuestionAnswers")
}
The following (and variants of it) fail:
mutation CreateAnswer {
createAnswer(input: {
text:"Yes",
question: {
id: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
}
})
{
id
}
}
Serverside code:
mutation CreateAnswer($input: CreateAnswerInput!) {
createAnswer(input: $input) {
id
text
question {
id
text
answers {
nextToken
}
}
}
}
With the above, receiving the following error:
"Validation error of type WrongType: argument 'input' with value
'ObjectValue{objectFields=[ObjectField{name='text',
value=StringValue{value='3'}}, ObjectField{name='question',
value=ObjectValue{objectFields=[ObjectField{name='id',
value=StringValue{value='9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8'}}]}}]}'
contains a field not in 'CreateAnswerInput': 'question' #
'createAnswer'"
Seems that this may be a naming convention in AppSync. The below worked for me:
mutation createAnswer {
createAnswer (input: {
text: "5"
answerQuestionId: "9d38c759-6b64-4c1f-9e0e-d3b95a72b3a8"
}) {
id
}
Adding answer to QuestionId was what was needed.

KeystoneJS show error for unqiue index failure

I have a model for tracking redirects like so:
var Redirect = new keystone.List('Redirect', {
});
Redirect.add({
from: { type: String, required: true, initial: true, unique: true },
to: { type: String, required: true, initial: true },
status: { type: Types.Select, options: [{value: 302, label: 'Temporary'},{value: 301, label: 'Permanent'}], default: 302, numeric: true, initial: true }
});
The unique constraint works, I can create new models as long as it doesn't fail to have a unique 'from', but when I do create one with a non-unique 'from' I get an error in the server console but the frontend does nothing.
Error saving changes to Redirect 5664d5860d7c730f09880de1: {
[MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key
error index: keystone.redirects.$from_1 dup key: { : "/herp" }]
name: 'MongoError', code: 11000, err: 'insertDocument :: caused by
:: 11000 E11000 duplicate key error index: keystone.redirects.$from_1
dup key: { : "/herp" }' }
Is there another setting I need to do to get the error to show on the frontend so the user knows what went wrong?
You will have to catch that error in your server logic and present a friendlier flash message to your visitors. At least the database error message is descriptive of the problem duplicate key error ...
exports.flashMessages = function(req, res, next) {
var flashMessages = {
error: req.flash('error')
};
res.locals.messages = _.any(flashMessages,
function(msgs) { return msgs.length }) ? flashMessages
: false;
next();
};
See Common Route Middleware
and to customize the message ensure the passed object contains the appropriate fields for the template
you can provide flash messages in your server logic by adding req.flash
req.flash(
'success',
'Your job has been submitted. Allow 30 days for approval.'
);
See https://github.com/r3dm/shpesfba.org/blob/b83d9e6a3859a83f4b4738e7a13ead08ce611bd3/routes/views/jobForm.js#L44
To display a flash error in the adminUI create an error object and pass that back into the next callback like so
Redirect.schema.pre('save', function(next) {
if (saveFailure) {
var err = new Error('MongoDB is barfing on this');
next(err);
}
}
The difficult part will be to craft your logic with mongoose pre and post lifecycle hooks to catch the mongodb error. Please do some experimenting.
See https://github.com/r3dm/shpesfba.org/blob/b83d9e6a3859a83f4b4738e7a13ead08ce611bd3/models/Event.js#L76