Go Swagger: Could not resolve pointer: /definitions/Instant - go

We're using Go Swagger for generating the API documentation.
When I run SwaggerUI, I receive this message:
Resolver error at
paths./api/v1/member.get.responses.200.schema.items.$ref Could not
resolve reference: Could not resolve pointer: /definitions/Instant
does not exist in document Resolver error at
paths./api/v1/member.get.responses.401.schema.$ref Could not resolve
reference: Could not resolve pointer: /definitions/EmptyResponse does
not exist in document
What am I doing wrong?
This is what is defined in to annotate:
// swagger:operation GET /api/v1/member Elig Elig
//
// Get Member Elig.
//
// ---
// produces:
// - application/json
//
// parameters:
// - name: memberId
// in: query
// description: Member Info
// type: string
// - name: eligStart
// in: query
// description: Input Date of Elig Start
// type: string
// - name: eligEnd
// in: query
// description: Input Date of Elig End
// type: string
// responses:
// '200':
// description: Successful response. It returns Transactional Data from the Vendor
// schema:
// type: array
// items:
// "$ref": "#/definitions/Instant"
// '401':
// description: Empty response.
// schema:
// "$ref": "#/definitions/EmptyResponse"

Related

Error: Expected [object Object] to be a possible input type, saw GraphQLObjectType(Category)

I am trying to get trying to create a Product with the following fields, however whenever I try to have my categories object within my Product Object equal an actual Category Object that is already made I get the error above.
I want to have an [Category] be the value of the categories field within my Product Object, I hope that makes sense.
import {Category} from "./Category"
export const ProductMutation = extendType({
type: "Mutation",
definition(t) {
//create a new item
t.nonNull.field('createProduct', {
type:'Product',
args: {
id: stringArg(),
name: nonNull(stringArg()),
description: (stringArg()),
ingredients: list(stringArg()),
img: (stringArg()),
moveActive: (booleanArg()),
price: (floatArg()),
category: list(stringArg()), // this needs to be type Category and then i should be good
//tried category: list(arg({ type: Category})), (this didn't work)
},
resolve(_root, args, ctx) {
return ctx.prisma.product.create({
data: {
name: args.name,
description: args.description,
ingredients: args.ingredients,
img: args.img,
moveActive: args.moveActive,
price: args.price,
category: args. category
}
})
}
})
}
})

Apollo-client: Add item to array in cache

Suppose I have the following GraphQL types:
type User {
id: String!
posts: [Post!]!
}
type Post {
id: String!
text: String,
}
And here is a mutation that returns the updated post:
mutation addNewPost(
$userId: String!
$text: String!
) {
addNewPost(userId: $userId, text: $text) {
id
text
}
}
After running this mutation my cache contains a new entry of a post. How do I add it to the user's posts array? I have tried cache.writeQuery and cache.modify but I cannot figure it out.
We do push the item into array inside the update function, which is one of the options of useMutation.
I'm writing the whole mutation so that you can get the idea 💡, let have a look at example:
By Update function:
const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
update(cache, response) {
// Here we write the update
// Step 1: Read/Fetch the data 👈
const data = client.readQuery({
query: FETCH_POSTS_QUERY,
});
// Step 2: Update the cache by immutable way 👈
client.writeQuery({
query: FETCH_POSTS_QUERY,
data: {
getPosts: [response.data.createPost, ...data.getPosts],
},
});
},
variables: formValues,
});
By refetchQueries:
That's really shortcut 🔥 way to update the cache, by using DocumentNode object parsed with the gql function
const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
refetchQueries: [ 👈
FETCH_POSTS_QUERY
'fetchPosts`' // OR Query name
],
variables: formValues,
});
You're going to want to directly write to the Apollo cache in order to update the other entities that your mutation has modified.
Have a look at the docs https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates here for specifics (you're going to want to use cache.modify and cache.writeFragment)

Post validation failed: title: Path `title` is required.", in graphql

I trying to add mutation in graphql-yoga but every time I try to mutate the I get error saying
Post validation failed: title: Path title is required.",
I have no idea why.
Here is my code
resolver
Mutation: {
createPost: async(root, args, ctx) => {
console.log(args)
try {
const post = new Post({
title: args.title,
description: args.description,
content: args.content
});
const result = await post.save();
console.log(result);
return result
}catch(err) {
throw err
}
}
}
schema
input postInput{
title: String!
description: String!
content: String!
}
type Mutation {
createPost(input: postInput): Post!
}
This works fine if I remove the input type and directly do like this
type Mutation {
createPost(title: String!,description: String!,content: String!): Post!
}
log result
{ input:
[Object: null prototype] {
title: 'with input',
description: 'this is de',
content: 'this is conte' } }
Here Why am I getting [Object: null prototype]?
You have to send your data in your resolver like this if you give input type like this on schema:
const post = new Post({
title: args.input.title,
description: args.input.description,
content: args.input.content
});
It means, in args, we need a parameter called input which is of type Post.
And while giving the datas on graphql gui send data like this:
mutation {
createPost(input:{
title: 'with input',
description: 'this is de',
content: 'this is conte'}) {
//return your id or others
}
}

JSON schema validation with perfect messages

I have divided the data entry in a REST call in 4 parts. Data can be sent to REST call via:-
headers
query params
path params
request body
So in order to validate the presence of any key in any of the above 4 parts I have created a schema in this format. So if in case I have to validate anything in query params I will add the key 'query' and then add the fields inside that, that needs to be validated
const schema = {
id: 'Users_login_post',
type: 'object',
additionalProperties: false,
properties: {
headers: {
type: 'object',
additionalProperties: false,
properties: {
Authorization: {
type: 'string',
minLength: 10,
description: 'Bearer token of the user.',
errorMessages: {
type: 'should be a string',
minLength: 'should be atleast of 23 length',
required: 'should have Authorization'
}
}
},
required: ['Authorization']
},
path: {
type: 'object',
additionalProperties: false,
properties: {
orgId: {
type: 'string',
minLength: 23,
maxLength: 36,
description: 'OrgId Id of the Organization.',
errorMessages: {
type: 'should be a string',
minLength: 'should be atleast of 23 length', // ---> B
maxLength: 'should not be more than 36 length',
required: 'should have OrgId'
}
}
},
required: ['orgId']
}
}
};
Now, in my express code, I created a request object so that I can test the validity of the JSON in this format.
router.get("/org/:orgId/abc", function(req, res){
var request = { //---> A
path: {
orgId : req.params.orgId
},
headers: {
Authorization : req.headers.Authorization
}
}
const Ajv = require('ajv');
const ajv = new Ajv({
allErrors: true,
});
let result = ajv.validate(schema, request);
console.log(ajv.errorsText());
});
And I validate the above request object (at A) against my schema using AjV.
The output what I get looks something like this:
data/headers should have required property 'Authorization', data/params/orgId should NOT be shorter than 23 characters
Now I have a list of concerns:
why the message is showing data word in the data/headers and data/params/orgId even when my variable name is request(at A)
Also why not my errormessages are used, like in case of orgId I mentioned: should be atleast of 23 length (at B) as a message, even then the message came should NOT be shorter than 23 characters.
How can I show request/headers instead of data/headers.
Also, the way I used to validate my path params, query params, header params, body param, is this the correct way, if it is not, then what can be the better way of doing the same?
Please shed some light.
Thanks in advance.
Use ajv-keywords
import Ajv from 'ajv';
import AjvKeywords from 'ajv-keywords';
// ajv-errors needed for errorMessage
import AjvErrors from 'ajv-errors';
const ajv = new Ajv.default({ allErrors: true });
AjvKeywords(ajv, "regexp");
AjvErrors(ajv);
// modification of regex by requiring Z https://www.regextester.com/97766
const ISO8601UTCRegex = /^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(.[0-9]+)?Z$/;
const typeISO8601UTC = {
"type": "string",
"regexp": ISO8601UTCRegex.toString(),
"errorMessage": "must be string of format 1970-01-01T00:00:00Z. Got ${0}",
};
const schema = {
type: "object",
properties: {
foo: { type: "number", minimum: 0 },
timestamp: typeISO8601UTC,
},
required: ["foo", "timestamp"],
additionalProperties: false,
};
const validate = ajv.compile(schema);
const data = { foo: 1, timestamp: "2020-01-11T20:28:00" }
if (validate(data)) {
console.log(JSON.stringify(data, null, 2));
} else {
console.log(JSON.stringify(validate.errors, null, 2));
}
https://github.com/rofrol/ajv-regexp-errormessage-example
AJV cannot know the name of the variable you passed to the validate function.
However you should be able to work out from the errors array which paths have failed (and why) and construct your messages from there.
See https://ajv.js.org/#validation-errors
To use custom error messages in your schema, you need an AJV plugin: ajv-errors.
See https://github.com/epoberezkin/ajv-errors

Sailjs with sails-mongo is enforcing type incorrectly. What am I doing wrong?

I have a sails app working with just a simple index and simple create (insert) to a mongo db. When I enter correctly typed data hard coded to be the type stated in the model, I get an error.
url insert err = [Error (E_VALIDATION) 1 attribute is invalid] Invalid attributes sent to urls:
• status
• Value should be a number (instead of "0", which is a string)
This is a very small, new project so not a lot of settings have been changed from default.
Since I have console.log in the create, I can see exactly what I' sending to the urls.create:
{ url: 'http://www.dina.com',
status: 0,
statusDate: '2016-11-19T19:46:10.804Z' }
I'm not doing anything to enforce type and it looks like I'm obeying type. Why am I getting error?
The model looks like:
// urls.js
module.exports = {
attributes: {
url : { type: 'string' },
status: { type: 'number'},
statusDate: {type: 'date'}
}
};
My config/models.js has schema set to false:
// config/models.js
module.exports.models = {
connection: 'DigitalOceanMongodbServer',
migrate: 'safe',
schema: false
};
My controller creates a new object with hard-coded status and statusDate of the correct type:
// urlsController.js
create: function (req, res) {
let url = req.body.url;
if(!url) return res.json({failure: 'empty url'});
let isValid = sails.validurl.isUri(url);
if(!isValid) return res.json({failure: 'url is not valid'});
let newObj = {
url: url,
status: 0, <---- obviously a number
statusDate: new Date().toISOString() <---obviously a date
}
console.log(newObj);
urls.create(newObj).exec(function createCB(err,created){
if (err){
return res.negotiate(err);
} else {
return res.ok(created);
}
});
}
Specify "integer" instead of "number" in the type of your model. I did not find "number" in the docs.
See: http://sailsjs.org/documentation/concepts/models-and-orm/attributes

Resources