私はgraphqlスキーマとして次のコードを持っていると仮定します。 A userType
にはid
とname
が含まれており、2種類のクエリ:allUsers: [userType]
とuser(id: Int!): userType
があります。実行時にGraphQLObjectTypeフィールドを変更する
let db = [{
id: 1,
name: 'Amir'
}, {
id: 2,
name: 'John'
}];
const userType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLInt },
name: { type: GraphQLString }
}
});
const queryType = new GraphQLObjectType({
name: 'Query',
fields: {
allUsers: {
type: new GraphQLList(userType),
resolve:() => db
},
user: {
type: userType,
args: {
id: { type: new GraphQLNonNull(GraphQLInt) }
},
resolve: (_, { id }) => db.find(user => user.id == id);
}
}
})
let schema = new GraphQLSchema({ query: queryType });
私は、ブート時にこの構造を変更する必要があります。最後の行を実際に実行する前に意味します。
さらに多くの種類のクエリを追加するために、すべての変更が完了したら、最後にスキーマの作成(new GraphQLSchema(...)
)を延期しました。したがって、クエリ自体にフィールドを追加したり、既存のフィールドを変更したりすることができます。
しかしどのように私はすでにに定義されてい種類を変更ことができますか?基本的にはpermissions
のようなuserType
に他のフィールドを追加する必要があります。それ自体はGraphQLObjectType
であり、独自のresolve
機能を持っています。このような
何か:
let queryFields = {};
const userType = new GraphQLObjectType({
name: 'User',
fields: {
id: { type: GraphQLInt },
name: { type: GraphQLString }
}
});
queryFields['allUsers'] = {
type: new GraphQLList(userType),
// ...
}
queryFields['user'] = {
type: userType,
//...
}
/* HERE <---------------------------------------- */
userType.fields.permission = {
type: GraphQLString,
resolve: user => getPermissionsFor(user);
}
const queryType = new GraphQLObjectType({
name: 'Query',
fields: queryFields
})
var schema = new GraphQLSchema({ query: queryType });
ありがとう!
([GraphQLObjectTypeのソースコード] https://github.com/graphql/graphql-js/blob/3cb4ceaeaa14b8f96d1c2f0b830222e3ab16cf60/src/type/definition.js#L392 -L433)は、実行時の変更が不可能であることを示します。フィールドは作成時に固定されています。 –