I am writing a mutation for a GraphQL schema:
const Schema = new GraphQLSchema({
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: () => ({
person: {
type: GraphQLString,
args: {
name: {type: GraphQLString},
school: {type: GraphQLString},
},
resolve: mutatePerson,
},
}),
}),
});
I want to ensure that mutatePerson will only work if both name and school arguments are present. How can I check that?
The GraphQLNonNull type wrapper is used to specify both fields and arguments as non-null. For fields, that means the value of the field in the query results cannot be null. For arguments, that means that the argument cannot be left out or have a value of null. So your code just needs to look more like this:
args: {
name: {
type: new GraphQLNonNull(GraphQLString),
},
school: {
type: new GraphQLNonNull(GraphQLString),
},
},
it is better to do it as follow (in the model) if you want to reject empty Strings like "", it is different from Null, this way you can reject both Null and empty "".
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const buinessSchema = new Schema({
name: { type: String, required: true, unique: true },
address: { type: String, required: true },
phone: { type: String, required: true },
email: { type: String, required: true },
website: { type: String, required: true },
currency: { type: String, required: true },
aboutus: { type: String, required: true },
terms: String,
slogan: String,
logo: { type: String, required: true }
});
module.exports = mongoose.model("Buiness", buinessSchema);
Related
I have a problem with typing GraphQLInputObjectType. I can't find a way to inherit Prisma 2 types.
There is no problem when I type them manually for create, delete and other similar inputs, but prisma 2 has some very complex filters that are hard to manually type.
This is what prisma 2 where types are
Prisma 2 types for "where" property
export type PersonOrganisationRoleWhereInput = {
AND?: Enumerable<PersonOrganisationRoleWhereInput>
OR?: Enumerable<PersonOrganisationRoleWhereInput>
NOT?: Enumerable<PersonOrganisationRoleWhereInput>
id?: IntFilter | number
nickname?: StringFilter | string
person?: XOR<PersonRelationFilter, PersonWhereInput>
personId?: IntFilter | number
role?: XOR<RoleRelationFilter, RoleWhereInput>
roleId?: IntFilter | number
organisation?: XOR<OrganisationRelationFilter, OrganisationWhereInput>
organisationId?: IntFilter | number
created?: DateTimeFilter | Date | string
updated?: DateTimeNullableFilter | Date | string | null
expired?: DateTimeNullableFilter | Date | string | null
Seafarer?: SeafarerListRelationFilter
}
StringFilter (Just one of many)
export type StringFilter = {
equals?: string
in?: Enumerable<string>
notIn?: Enumerable<string>
lt?: string
lte?: string
gt?: string
gte?: string
contains?: string
startsWith?: string
endsWith?: string
search?: string
mode?: QueryMode
not?: NestedStringFilter | string
}
My manual typing of graphqlInputType
export const PersonOrganisationRoleWhereInput: GraphQLInputObjectType =
new GraphQLInputObjectType({
name: 'PersonOrganisationRoleWhereInput',
fields: () => ({
id: { type: GraphQLID },
roleId: { type: GraphQLInt },
name: { type: StringFilter },
created: { type: GraphQLString },
updated: { type: GraphQLString },
expired: { type: GraphQLString },
AND: { type: GraphQLList(PersonOrganisationRoleWhereInput) },
OR: { type: GraphQLList(PersonOrganisationRoleWhereInput) },
NOT: { type: GraphQLList(PersonOrganisationRoleWhereInput) },
}),
});
My manual typing of StringFilter
export const StringFilter = new GraphQLInputObjectType({
name: 'StringFilter',
fields: () => ({
equals: { type: GraphQLString },
not: { type: GraphQLString },
in: { type: GraphQLList(GraphQLString) },
notIn: { type: GraphQLString },
lt: { type: GraphQLString },
lte: { type: GraphQLString },
gt: { type: GraphQLString },
gte: { type: GraphQLString },
contains: { type: GraphQLString },
mode: { type: GraphQLString },
}),
});
Now the problem is that prisma 2 has many types and it would take a long time to manually adjust it to GraphQLInputObjectType. Especially when they add new things with each update.
WHY DO I NEED IT?
When passing args to Apollo useQuery/useMutation, graphql blocks the request as some prisma 2 types do not match my GraphQLInputObjectType. Types must match perfectly in order for it to pass.
For example:
//Prisma 2 type
id?: IntFilter | number
I cannot type GraphQLInputObjectType as prisma 2 type, as I can either set it as IntFilter or number. If it is IntFilter, I can't set a number as argument, even tho prisma 2 accepts both values.
Is there a simple way to inherit those properties inside GraphQLInputObjectType?
Im not familiar with prisma2, however we autogenerated our graphql input types. Maybe this will help?
I've trying to set the default value of a prop to a local value using i18n. I'm using Vue 3.2 and the script setup tag.
I've tried the following but this gives me an error:
defineProps are referencing locally declared variables.
<script setup>
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
defineProps({
type: { type: String, required: true },
title: { type: String, required: false, default: `${t('oops', 1)} ${t('request_error', 1)}` },
description: { type: String, required: false, default: '' },
showReload: { type: Boolean, required: false, default: false },
error: { type: String, required: true },
});
</script>
What's the best way to handle this?
defineProps is a compiler macro, so you can't use any runtime values within it. I'd suggest to use a local variable for this default:
<script setup>
import { useI18n } from 'vue-i18n';
const props = defineProps({
type: { type: String, required: true },
title: { type: String, required: false},
description: { type: String, required: false, default: '' },
showReload: { type: Boolean, required: false, default: false },
error: { type: String, required: true },
});
const { t } = useI18n();
const titleWithDefault = props.title || `${t('oops', 1)} ${t('request_error', 1)}`;
</script>
Also described here in the last bullet point: https://v3.vuejs.org/api/sfc-script-setup.html#defineprops-and-defineemits
if you want Default props values when using type declaration use this:
export interface Props {
msg?: string
labels?: string[]
}
const props = withDefaults(defineProps<Props>(), {
msg: 'hello',
labels: () => ['one', 'two']
})
learn more here
I want to achieve the fields of one object type within another object type
Here is my schema file.
const Films = new GraphQLInterfaceType({
name: 'films',
fields: () => ({
id:{
type: GraphQLID
},
name: {
type: GraphQLString,
},
})
})
const MovieStream = new GraphQLObjectType({
name: 'MovieStream',
interfaces: () => [Films],
fields: () => ({
id: {
type: GraphQLID,
},
movie_id: {
type: GraphQLString,
},
})
})
Here I am trying to use the interface. But It shows error:
{
"errors": [
{
"message": "Query root type must be Object type, it cannot be { __validationErrors: undefined, __allowedLegacyNames: [], _queryType: undefined, _mutationType: undefined, _subscriptionType: undefined, _directives: [#include, #skip, #deprecated], astNode: undefined, extensionASTNodes: undefined, _typeMap: { __Schema: __Schema, __Type: __Type, __TypeKind: __TypeKind, String: String, Boolean: Boolean, __Field: __Field, __InputValue: __InputValue, __EnumValue: __EnumValue, __Directive: __Directive, __DirectiveLocation: __DirectiveLocation, films: films, ID: ID, Date: Date, JSON: JSON, MovieStream: MovieStream }, _possibleTypeMap: {}, _implementations: { films: [] } }."
},
{
"message": "Expected GraphQL named type but got: { __validationErrors: undefined, __allowedLegacyNames: [], _queryType: undefined, _mutationType: undefined, _subscriptionType: undefined, _directives: [#include, #skip, #deprecated], astNode: undefined, extensionASTNodes: undefined, _typeMap: { __Schema: __Schema, __Type: __Type, __TypeKind: __TypeKind, String: String, Boolean: Boolean, __Field: __Field, __InputValue: __InputValue, __EnumValue: __EnumValue, __Directive: __Directive, __DirectiveLocation: __DirectiveLocation, films: films, ID: ID, Date: Date, JSON: JSON, MovieStream: MovieStream }, _possibleTypeMap: {}, _implementations: { films: [] } }."
}
]
}
Here is Query type:
const QueryRoot = new GraphQLObjectType({
name: 'Query',
fields: () => ({
getContentList:{
type: new GraphQLList(contentCategory),
args: {
id: {
type: GraphQLInt
},
permalink: {
type: GraphQLString
},
language: {
type: GraphQLString
},
content_types_id: {
type: GraphQLString
},
oauth_token:{
type: GraphQLString
}
},
resolve: (parent, args, context, resolveInfo) => {
var category_flag = 0;
var menuItemInfo = '';
user_id = args.user_id ? args.user_id : 0;
// console.log("context"+context['oauth_token']);
return AuthDb.models.oauth_registration.findAll({attributes: ['oauth_token', 'studio_id'],where:{
// oauth_token:context['oauth_token'],
$or: [
{
oauth_token:
{
$eq: context['oauth_token']
}
},
{
oauth_token:
{
$eq: args.oauth_token
}
},
]
},limit:1}).then(oauth_registration => {
var oauthRegistration = oauth_registration[0]
// for(var i = 0;i<=oauth_registration.ength;i++){
if(oauth_registration && oauthRegistration && oauthRegistration.oauth_token == context['oauth_token'] || oauthRegistration.oauth_token == args.oauth_token){
studio_id = oauthRegistration.studio_id;
return joinMonster.default(resolveInfo,{}, sql => {
return contentCategoryDb.query(sql).then(function(result) {
return result[0];
});
} ,{dialect: 'mysql'});
}else{
throw new Error('Invalid OAuth Token');
}
})
},
where: (filmTable, args, context) => {
return getLanguage_id(args.language).then(language_id=>{
return ` ${filmTable}.permalink = "${args.permalink}" and ${filmTable}.studio_id = "${studio_id}" and (${filmTable}.language_id = "${language_id}" OR ${filmTable}.parent_id = 0 AND ${filmTable}.id NOT IN (SELECT ${filmTable}.parent_id FROM content_category WHERE ${filmTable}.permalink = "${args.permalink}" and ${filmTable}.language_id = "${language_id}" and ${filmTable}.studio_id = "${studio_id}"))`
})
},
}
})
})
module.exports = new GraphQLSchema({
query: QueryRoot
})
Please help me out. have i done something wrong in the use of interface?
I have found the answer through this post
Is it possible to fetch data from multiple tables using GraphQLList
Anyone please tell me the exact way to use the interface in my code.
Although the error you have printed does not really relate to interfaces implementations, in order for you to use interfaces, you have to implement the methods/types the interface references. So in your situation your object MovieStream is missing the type name that you refer in the object Films.
Your code should look something like:
const Films = new GraphQLInterfaceType({
name: 'films',
fields: () => ({
id:{
type: GraphQLID
},
name: {
type: GraphQLString,
},
})
})
const MovieStream = new GraphQLObjectType({
name: 'MovieStream',
interfaces: () => [Films],
fields: () => ({
id: {
type: GraphQLID,
},
name: {
type: GraphQLString // You're missing this!
},
movie_id: {
type: GraphQLString,
},
})
})
Now back to the error you have printed "message": "Query root type must be Object type, it cannot be...
This seems to be related to your QueryRoot object, it seems that GraphQLSchema is not recognizing the root object. If this issue is still there once you fix the interface, have a look at this answer here
I am having some difficulty getting a mutation working in GraphQL where the type in the schema includes a nested type. So say I have a data type for a booking:
const BookingType = new GraphQLObjectType({
name: 'Booking',
fields: () => ({
id: { type: GraphQLInt },
Date: { type: GraphQLString },
Venue: { type: GraphQLString }
})
});
In the schema file I also have a root mutation which looks like this:
createBooking: {
type: BookingType,
args: {
Date: { type: new GraphQLNonNull(GraphQLString) },
Venue: { type: new GraphQLNonNull(GraphQLString) }
},
resolve(parentValue, args){
return axios.post('http://localhost:3000/booking', args)
.then(resp => resp.data);
}
}
I can write a mutation in GraphiQL to create data for the booking no problem:
mutation {
createBooking(
Date: "2018-03-12",
Venue: "Some place",
) {
id
Date
Venue
}
}
So far so good. Now, I need to add a nested type to the original booking object to record staff members assigned to the booking. So I added types for the staff member (both input and output types) and added those to the Booking type and the mutation:
// output type
const AssignedStaffType = new GraphQLObjectType({
name: 'AssignedStaff',
fields: () => ({
id: { type: GraphQLInt },
Name: { type: GraphQLString }
})
});
// input type
const AssignedStaffInputType = new GraphQLInputObjectType({
name: 'AssignedStaffInput',
fields: () => ({
id: { type: GraphQLInt },
Name: { type: GraphQLString }
})
});
The booking type becomes:
const BookingType = new GraphQLObjectType({
name: 'Booking',
fields: () => ({
id: { type: GraphQLInt },
Date: { type: GraphQLString },
Venue: { type: GraphQLString },
Staff: { type: new GraphQLList(AssignedStaffType) }
})
});
And the root mutation becomes:
createBooking: {
type: BookingType,
args: {
Date: { type: new GraphQLNonNull(GraphQLString) },
Venue: { type: new GraphQLNonNull(GraphQLString) },
Staff: { type: new GraphQLList(AssignedStaffInputType) }
},
resolve(parentValue, args){
return axios.post('http://localhost:3000/booking', args)
.then(resp => resp.data);
}
}
What I don't know is how to now formulate the mutation in GraphiQL, specifically what to use as a value for Staff:
mutation {
createBooking(
Date: "2018-03-14",
Venue: "Some place",
Staff: // ??? <--- What goes here??
) {
id
Venue
Date
Staff
}
}
I have tried giving it an object, or an array of objects which have the same structure as AssignedStaffInputType, but I just get an error ('expecting AssignedStaffInputType'). The client (GraphiQL in this instance) doesn't know anything about the AssignedStaffInputType as defined in the schema, so I don't understand a) how to use this input type in the client, or b) how I would then populate such a type with the required data.
Help please!
Never mind, I figured it out. I can, in fact, pass an object (or array of objects) in the correct format (specified in the input type in the schema) and it works fine. The reason I was having problems is that I had the wrong scalar type for one of the fields in the input type and this was throwing the error. The client doesn't need to know about the types specified in the schema it seems. So, the above problematic mutation should, in fact, be written like this:
mutation {
createBooking(
Date: "2018-03-14",
Venue: "Some place",
Staff: [{staffId: 1}]
) {
id
Venue
Date
Staff{
Name
}
}
}
I have some GraphQL types:
const Atype = new GraphQLObjectType({
name: 'Atype',
fields: {
data: { type: ADataType },
error: { type: GraphQLString },
}
})
and
const Btype = new GraphQLObjectType({
name: 'Btype',
fields: {
data: { type: BDataType },
error: { type: GraphQLString },
}
})
It looks redundant because only data fields are different...
How can I solve it in more elegant way in GraphQL ?
I created a new Type named Mixed just to solve similar issue., Mixed works as mongoose Mixed type, If you're familiar with it.
Create a new file named GraphQLMixed.js or name it whatever you want and place this code inside it.
import { GraphQLScalarType } from 'graphql';
const GraphQLMixed = new GraphQLScalarType({
name: 'Mixed',
serialize: value => value,
parseValue: value => value,
parseLiteral: ast => ast.value
});
export default GraphQLMixed;
Now, Based on your syntax I assume you're using express-graphql, So wherever you want to use this type, Do this
const GraphQLMixed = require('path/to/file/GraphQLMixed');
const Atype = new GraphQLObjectType({
name: 'Atype',
fields: {
data: { type: GraphQLMixed },
error: { type: GraphQLString },
}
})
const Btype = new GraphQLObjectType({
name: 'Btype',
fields: {
data: { type: GraphQLMixed },
error: { type: GraphQLString },
}
})
Hope this works and helps.