How to create joi schema to validate object of objects - validation

I tried to make schema to validate json such this:
{
"integration": { "module": [ "m" ] },
"tile": {
"title": "TTT",
"text": "ttt",
"icon": "./resources/main-icon.png",
"tags": [ "bbb", "vvvv"],
"orderNumber": 20
},
"steps": {
"order": [
"1",
"2",
"3"
],
"data": {
"1": {
"title": "tt1",
"description": "",
"screens": { "default": "true" }
},
"2": {
"title": "tt2",
"description": "",
"screens": { "default": "true" }
},
"3": {
"title": "tt3",
"description": "",
"screens": { "default": "true" }
}
}
}
};
Schema:
Joi.object({
integration: Joi.object({
module: Joi.array().items(Joi.string().valid('m').required())
}).required(),
tile: Joi.object({
title: Joi.string().required(),
text: Joi.string().required(),
icon: Joi.string().required(),
tags: Joi.array().items(Joi.string()).required(),
orderNumber: Joi.number().integer().min(1).max(255).required()
}).required(),
steps: Joi.object({
order: Joi.array().items(Joi.string()).required(),
data: Joi.object().keys({
title: Joi.string().required(),
description: Joi.string().required(),
screens: Joi.object({
default: Joi.string().valid('true', 'false').required()
}).required()
}).unknown(),
}).required()
});
But it generate error:
Validation Error: "steps.data.title" is required. "steps.data.description" is required. "steps.data.screens" is required
Please help. How can I make this schema?

Your data key is an object with keys 1, 2, and 3, each one is also an object with keys title, description, and screens.
But in your validation, your data key is an object with keys title, description, and screens, which is not correct.
You should change your steps.data validation to this:
data: Joi.object().pattern(
Joi.string().valid("1", "2", "3"),
Joi.object().keys({
title: Joi.string().required(),
description: Joi.string().required().allow(''),
screens: Joi.object({ default: Joi.string().valid('true', 'false').required() }),
})).unknown(),
}).required()
I used Joi.object().pattern to avoid duplicating the code since your object value is the same for each key.
I also changed your data.description, since you were not allowing empty strings, I just added .allow('').

Related

contentful graphql nested structure

I have a page in contentful which I retrieve content to my react app with graphql.
In this page, a link a content model called Person which is like that:
{
"name": "Person",
"description": "",
"displayField": "name",
"fields": [
{
"id": "name",
"name": "Name",
"type": "Symbol",
"localized": false,
"required": true,
"validations": [],
"disabled": false,
"omitted": false
},
{
"id": "profilePic",
"name": "profile pic",
"type": "Link",
"localized": false,
"required": true,
"validations": [],
"disabled": false,
"omitted": false,
"linkType": "Asset"
},
{
"id": "socialLinks",
"name": "social links",
"type": "Array",
"localized": false,
"required": false,
"validations": [],
"disabled": false,
"omitted": false,
"items": {
"type": "Link",
"validations": [
{
"linkContentType": [
"socialLink"
]
}
],
"linkType": "Entry"
}
}
ProfilePic is another content model which include name and picUrl.
SocialLinks is an array of socialLink content model which contain name and link
I can retrieve without problem my profilePic name or picUrl but I cannot get the socialLinks.
I have read the contentful documentation about one-to-many but is not clear to me how to apply to my case: https://www.contentful.com/developers/docs/references/graphql/#/reference/schema-generation/one-to-many-multi-type-relationships
My query:
...rest of the query..
founder{
name,
profilePic{
url,
title
},
socialLinksCollection {
items {
name,
link
}
}
},
... rest of the query...
Can somoene help me understand why it doesn't work as a normal collection?
Should I maybe use this concept of linkedFrom? But how exactly?
I had to add (limit: 1) to my socialLinksCollections otehrwise there were too many calls and wasn't possible to get the data back.
Thanks to #stefan judis for the suggestion where to look out for the errors.

Need Mongodb schema validator script for the given schema

Hi all i have been trying out various combination in the last few days to pinpoint how to create schema validator. Meaning a collection wont just take any input but will accept only what is given in the validator.
I created below collection via mongo-repository in spring.
Can you please provide the validator for the same. And also give links which will do complex mongodb collections to java pojo mapping. It would be of great help. All i found was simple validators or java to mongo collection not vice versa
{
"_id": {
"$numberInt": "1"
},
"listOfItems": [
{
"itemid": {
"$numberInt": "1"
},
"qty": {
"$numberInt": "10"
},
"qty_type": "kg",
"cost": "20",
"currency": "INR"
},
{
"itemid": {
"$numberInt": "2"
},
"qty": {
"$numberInt": "10"
},
"qty_type": "kg",
"cost": "20",
"currency": "INR"
},
{
"itemid": {
"$numberInt": "3"
},
"qty": {
"$numberInt": "10"
},
"qty_type": "kg",
"cost": "20",
"currency": "INR"
}
],
"_class": "com.daily.essential.cartservice.model.Cart"
}
//this should answer your question
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
//mongoose generates a new rando unique Id for the product
_id: mongoose.Schema.Types.ObjectId,
//mongoose makes sure that the name input by the user is a string and mongoose makes the /name field required that means the user must not leave the field empty.
name: {type: String, required: true},
//mongoose makes sure that the price input by the user is a a Number and mongoose makes //the price field required that means the user must not leave the field empty.
price: {type: Number, required: true}
});
module.exports = mongoose.model('Product', productSchema);

Unable to do a mutation with a property of type "array of objects" in apollo

I'm new to all graphql world, so this might be a very easy question, sorry
I'm using graphql-compose-mongoose to generate my graphql schema, here's my mongoose schema:
const ComplainSchema = new Schema({
entityId: {type: String, required: true},
user: {type: UserInfoSchema, required: true},
title: String, // standard types
desc: String,
state: {required: true, type: String, enum: ["DRAFT", "MODERATION", "PUBLIC", "SOLVED"]},
attachments: [{
url: {type: String, required: true},
name: String,
mimeType: String,
attachmentId: Schema.Types.ObjectId
}],
createdAt: {type: Date, index: true},
updatedAt: {type: Date, index: true},
}, {timestamps: {}})
export default mongoose.model('Complaint', ComplainSchema)
If I attempt the following mutation in graphiql it works fine
mutation {
complaintUpdateById(record:{_id:"5bdd9350fe144227042e6a20", title:"ok", desc:"updated", attachments:[{name:"zied", url:"http://zied.com"}]}){
recordId,
record{
_id,
entityId,
user {
userId,
userName,
roleInShop
},
title,
desc,
createdAt,
updatedAt,
attachments{
name,
url
}
}
}
}
and returns this (in case there could be helpful to see the response)
{
"data": {
"complaintUpdateById": {
"recordId": "5bdd9350fe144227042e6a20",
"record": {
"_id": "5bdd9350fe144227042e6a20",
"entityId": "5bd9b1858788f51f44ab678a",
"user": {
"userId": "5bd9ac078788f51f44ab6785",
"userName": "Zied Hamdi",
"roleInShop": "ASA"
},
"title": "ok",
"desc": "updated",
"createdAt": "2018-11-03T12:23:44.565Z",
"updatedAt": "2018-11-05T09:02:51.494Z",
"attachments": [
{
"name": "zied",
"url": "http://zied.com"
}
]
}
}
}
}
Now if I try to pass the attachments to apollo, I don't know how to do that, I don't know which type to provide (Attachment is not the right type obvisouly):
const UPDATE_COMPLAINT = gql `mutation complaintUpdateById($_id:MongoID!, $title: String!, $desc: String!, $attachments: [Attachment]
)
{
complaintUpdateById(record:{_id:$_id, title:$title, desc:$desc, attachments:$attachments}){
recordId,
record{
_id,
entityId,
user {
userId,
userName,
roleInShop
},
title,
desc,
createdAt,
updatedAt
}
}
}`
So searching for the right type, I did a introspection of my object, the issue is that I get the type of attachment as null for this query:
{
__type(name: "Complaint") {
kind
name
fields {
name
description
type {
name
}
}
}
}
this is the response:
{
"data": {
"__type": {
"kind": "OBJECT",
"name": "Complaint",
"fields": [
{
"name": "entityId",
"description": null,
"type": {
"name": "String"
}
},
{
"name": "user",
"description": null,
"type": {
"name": "ComplaintUser"
}
},
{
"name": "title",
"description": null,
"type": {
"name": "String"
}
},
{
"name": "desc",
"description": null,
"type": {
"name": "String"
}
},
{
"name": "state",
"description": null,
"type": {
"name": "EnumComplaintState"
}
},
{
"name": "attachments",
"description": null,
"type": {
"name": null
}
},
{
"name": "createdAt",
"description": null,
"type": {
"name": "Date"
}
},
{
"name": "updatedAt",
"description": null,
"type": {
"name": "Date"
}
},
{
"name": "_id",
"description": null,
"type": {
"name": null
}
}
]
}
}
}
googling didn't help since I don't know how is this operation called, I don't think it's a nested mutation from what I found...
Ok fixed,
I did these steps:
I first introspected the type of attachment in a regular query using the __typename keyword: as follows
mutation {
complaintUpdateById(record:{_id:"5bdd9350fe144227042e6a20", title:"ok", desc:"updated", attachments:[{name:"zied", url:"http://zied.com"}]}){
recordId,
record{
_id,
entityId,
user {
userId,
userName,
roleInShop
},
title,
desc,
createdAt,
updatedAt,
attachments{
__typename,
name,
url
}
}
}
}
it showed up a type named ComplaintAttachments
when replacing the Attachment type with this new value, ComplaintAttachments, an error occured and that error message helped me out:
Variable "$attachments" of type "[ComplaintAttachments]" used in
position expecting type "[ComplaintComplaintAttachmentsInput]"
so the array is of type ComplaintComplaintAttachmentsInput, I still don't know how to introspect it directly, but I'm already happy with the result :)

Mutation arguments as object

I'm using the Go implemenatation of GraphQL.
How would you configure a mutation so that it can receive arguments with more than 1 level?
For exemple, here is the list of arguments I would like to pass to a mutation CreateUser:
mutation createUser($user: CreateUser!) {
createUser(input: $user)
}
{
"user": {
"name": {
"first": "John",
"last": "Doe"
},
"email": "john#doe.com"
}
}
(Notice that I dont want to use firstname and lastname but a name object instead)
And this is my (unsuccessful) attempt so far:
var CreateUserInput = graphql.FieldConfigArgument{
"input": &graphql.ArgumentConfig{
Description: "Input for creating a new user",
Type: graphql.NewNonNull(graphql.NewInputObject(graphql.InputObjectConfig{
Name: "CreateUser",
Fields: graphql.InputObjectConfigFieldMap{
"name": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.NewInputObject(graphql.InputObjectConfig{
Fields: graphql.InputObjectConfigFieldMap{
"first": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
"last": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})),
},
"email": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})),
},
}
Apparently the subfields first and last are not recognized as this is what I get when I run this mutation:
{
"data": null,
"errors": [
{
"message": "Variable \"$user\" got invalid value {\"email\":\"john#doe.com\",\"name\":{\"first\":\"john\",\"last\":\"doe\"}}.\nIn field \"name\": In field \"first\": Unknown field.\nIn field \"name\": In field \"last\": Unknown field.",
"locations": [
{
"line": 1,
"column": 21
}
]
}
]
}
Is this even possible?
EDIT: See comments in the accepted answer for the solution.
This are my first ever lines of Go but I will try to convey what I think the problem is.
First lets talk about the structure you want to be going for. I will use SDL here:
type Mutation {
createUser(user: CreateUser!): Boolean! # Maybe return user type here?
}
input CreateUser {
name: CreateUserName!
email: String!
}
input CreateUserName {
first: String!
last: String!
}
Okay now that we know that we need two input types lets get started!
var CreateUserName = graphql.NewInputObject(graphql.InputObjectConfig{
Name: "CreateUserName",
Fields: graphql.InputObjectConfigFieldMap{
"first": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
"last": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})
var CreateUser = graphql.NewInputObject(graphql.InputObjectConfig{
Name: "CreateUser",
Fields: graphql.InputObjectConfigFieldMap{
"name": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(CreateUserName),
},
"email": &graphql.InputObjectFieldConfig{
Type: graphql.NewNonNull(graphql.String),
},
},
})
Now all that should be left is adding the mutation field to your mutation object type.

Apollo readQuery Fails Even Though Target Object is Present?

I'm working on a call to readQuery. I'm getting an error message:
modules.js?hash=2d0033b4773d9cb6f118946043f7a3d4385825fe:25847
Error: Can't find field resolutions({"id":"Resolution:DHSzPa8bvPCDjuAac"})
on object (ROOT_QUERY) {
"resolutions": [
{
"type": "id",
"id": "Resolution:AepgCCio9KWGkwyMC",
"generated": false
},
{
"type": "id",
"id": "Resolution:DHSzPa8bvPCDjuAac", // <==ID I'M SEEKING
"generated": false
}
],
"user": {
"type": "id",
"id": "User:WWv57KsvqWeAoBNHY",
"generated": false
}
}.
The object with that id appears to be plainly visible as the second entry in the list of resolutions.
Here's my query:
const GET_CURRENT_RESOLUTION_AND_GOALS = gql`
query Resolutions($id: String!) {
resolutions(id: $id) {
_id
name
completed
goals {
_id
name
completed
}
}
}
`;
...and here's how I'm calling it:
<Mutation
mutation={CREATE_GOAL}
update={(cache, {data: {createGoal}}) => {
let id = 'Resolution:' + resolutionId;
const {resolutions} = cache.readQuery({
query: GET_CURRENT_RESOLUTION_AND_GOALS,
variables: {
id
},
});
}}
>
What am I missing?
Update
Per the GraphQL Dev Tools extension for Chrome, here's the whole GraphQL data store:
{
"data": {
"resolutions": [
{
"_id": "AepgCCio9KWGkwyMC",
"name": "testing 123",
"completed": false,
"goals": [
{
"_id": "TXq4nvukpLcqQhMRL",
"name": "test goal abc",
"completed": false,
"__typename": "Goal"
},
],
"__typename": "Resolution"
},
{
"_id": "DHSzPa8bvPCDjuAac",
"name": "testing 345",
"completed": false,
"goals": [
{
"_id": "PEkg5oEEi2tJ6i8LH",
"name": "goal abc",
"completed": false,
"__typename": "Goal"
},
{
"_id": "X4H4dFzGm5gkq5bPE",
"name": "goal bcd",
"completed": false,
"__typename": "Goal"
},
{
"_id": "hYunrXsMq7Gme7Xck",
"name": "goal cde",
"completed": false,
"__typename": "Goal"
}
"__typename": "Resolution"
}
],
"user": {
"_id": "WWv57KsvqWeAoBNHY",
"__typename": "User"
}
}
}
Posted as answer for fellow apollo users with similar problems:
Remove the prefix of Resolution:, the query should only take the id.
Then the question arises how is your datastore filled?
To read a query from cache, the query needs to have been called with exactly the same arguments on the remote API before. This way apollo knows what the result for a field is with specific arguments. If you never called the remote endpoint with the arguments you want to use but know what the result would be, you can circumvent that and resolve the query locally by implementing a cache resolver. Have a look at the example in the documentation. Here the store contains a list of books (in your case resultions) and the query for a single book by id can be resolved with a simple cache lookup.

Resources