GraphQL 패키지 구성 유형 사용
9337 단어 javascriptwebdevgraphqlnode
지금 제 이메일 목록을 구독하려면 http://jauyeung.net/subscribe/으로 전화하십시오.
Express를 사용하여 간단한 GraphQL 서버를 만들 수 있습니다.이를 위해서는
express-graphql과 graphql팩이 필요합니다.본고에서 우리는
graphql 패키지 구축 모델을 사용할 수 있는 유형을 어떻게 추가하는지 연구할 것이다.구조 유형
우리는
GraphQLSchema 패키지에 부착된 graphql 구조 함수를 사용하여 프로그래밍 방식으로 모델을 구성할 수 있다.우리는 패턴 언어로
Query과 Mutation 유형을 정의할 필요가 없고, 그것들을 단독 대상 유형으로 만들 수 있다.예를 들어,
graphql.GraphQLObjectType 구조 함수를 사용하여 유형을 작성하고 객체 유형을 프로그래밍하여 다음 코드를 작성할 수 있습니다.const express = require('express');
const graphqlHTTP = require('express-graphql');
const graphql = require('graphql');
const userType = new graphql.GraphQLObjectType({
name: 'User',
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
}
});
let users = {
'1': {
id: '1',
name: 'Jane'
}
}
const queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: userType,
args: {
id: { type: graphql.GraphQLString }
},
resolve: (_, { id }) => {
return users[id];
}
}
}
});
const schema = new graphql.GraphQLSchema({ query: queryType });
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(3000, () => console.log('server started'));
위 코드에서는 userType GraphQL 데이터 유형을 다음과 같이 만들었습니다.const userType = new graphql.GraphQLObjectType({
name: 'User',
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
}
});
name 필드는 우리 유형의 이름을 정의하고 fields 대상은 우리가 유형에 포함하는 필드를 포함한다.우리는 id과 name을 String 유형으로 정의했다.그리고
Query 유형을 정의합니다.const queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: userType,
args: {
id: { type: graphql.GraphQLString }
},
resolve: (_, { id }) => {
return users[id];
}
}
}
});
위 코드에서 우리는 이 유형의 name을 Query으로 정의했다.우리가 포함하는 fields은 user 필드로 위에서 정의한 User 유형에 속한다.또한 문자열
id을 args 속성을 가진 매개 변수로 지정했습니다.마지막으로, 우리는 우리가 되돌려주고 싶은 내용을 되돌려주는
resolve 속성을 가지고 있습니다.본 예에서 우리는
User 대상에서 users으로 돌아가기를 희망한다. 왜냐하면 id이 매개 변수에 전달되기 때문이다.그런 다음 다음 다음 질의를 수행합니다.
{
user(id: "1"){
id
name
}
}
우리는 돌아왔다.{
"data": {
"user": {
"id": "1",
"name": "Jane"
}
}
}
users 객체에는 다음과 같은 내용이 포함되어 있습니다.let users = {
'1': {
id: '1',
name: 'Jane'
}
}
우리도 돌연변이를 똑같이 처리할 수 있다.이것은 특히 유용하다. 왜냐하면 우리는 데이터베이스 모델과 같은 다른 내용에서GraphQL 모델을 자동으로 만들기를 원하기 때문이다.데이터베이스 기록을 만들고 업데이트하는 데 있어서, 우리는 일반적인 형식이 있을 수 있습니다.
ES6 패브릭에 매핑되지 않는 결합 유형 등의 기능에도 사용할 수 있습니다.
그래픽 유형
우리는
GraphQLUnionType 구조 함수를 사용하여 연합 유형을 만들 수 있다.결합 유형을 작성하여 응용 프로그램에서 사용하려면 다음과 같이
GraphQLUnionType 구조 함수를 사용할 수 있습니다.const express = require('express');
const graphqlHTTP = require('express-graphql');
const graphql = require('graphql');
class Dog {
constructor(id, name) {
this.id = id;
this.name = name;
}
};
class Cat {
constructor(id, name, age) {
this.id = id;
this.name = name;
this.age = age;
}
};
const DogType = new graphql.GraphQLObjectType({
name: 'Dog',
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
}
});
const CatType = new graphql.GraphQLObjectType({
name: 'Cat',
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
age: { type: graphql.GraphQLInt },
}
});
const PetType = new graphql.GraphQLUnionType({
name: 'Pet',
types: [DogType, CatType],
resolveType(value) {
if (value instanceof Dog) {
return DogType;
}
if (value instanceof Cat) {
return CatType;
}
}
});
let pets = {
'1': new Dog('1', 'Jane'),
'2': new Cat('1', 'Jane', 11),
}
const queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: {
pet: {
type: PetType,
args: {
id: { type: graphql.GraphQLString }
},
resolve: (_, { id }) => {
return pets[id];
}
}
}
});
const schema = new graphql.GraphQLSchema({ query: queryType });
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(3000, () => console.log('server started'));
위의 코드에서 우리는 Dog과 Cat류를 데이터의 모델로 만들었다.그리고 GraphQL
Dog 및 Cat 유형을 다음과 같이 만듭니다.const DogType = new graphql.GraphQLObjectType({
name: 'Dog',
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
}
});
const CatType = new graphql.GraphQLObjectType({
name: 'Cat',
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
age: { type: graphql.GraphQLInt },
}
});
우리는 DogType과 CatType의 상수를 정의하여 Dog과 Cat의 대상 유형을 정의했다.Dog에는 id과 name, Cat에는 id, name과 age이 있습니다.그리고 우리는
Pet의 병합 유형을 정의했는데 이것은 Dog과 Cat의 병합이다. 아래와 같다.const PetType = new graphql.GraphQLUnionType({
name: 'Pet',
types: [DogType, CatType],
resolveType(value) {
if (value instanceof Dog) {
return DogType;
}
if (value instanceof Cat) {
return CatType;
}
}
});
우리는 types 방법과 resolveType 방법이 아니라 resolve 방법이 있다는 것을 주의하십시오.마지막으로 다음과 같은 방법으로 사용자에게 응답을 반환할 수 있도록 질의 유형을 작성했습니다.
const queryType = new graphql.GraphQLObjectType({
name: 'Query',
fields: {
pet: {
type: PetType,
args: {
id: { type: graphql.GraphQLString }
},
resolve: (_, { id }) => {
return pets[id];
}
}
}
});
resolve 함수는 pets을 통해 id 항목을 가져와 되돌려줍니다. 우리가 지정한 type은 PetType입니다.완료되면 다음과 같이 인라인 세션을 사용하여 질의할 수 있습니다.
{
pet(id: "1"){
__typename,
...on Dog {
id
name
}
...on Cat {
id
name
age
}
}
}
위의 조회에서 우리는 Dog 연산자를 사용하여 Cat과 ...on 필드를 구분한다.__typename에서 되돌아오는 대상의 유형을 가져옵니다.이 조회를 통해 우리는 다음과 같은 것을 얻어야 한다.
{
"data": {
"pet": {
"__typename": "Dog",
"id": "1",
"name": "Jane"
}
}
}
왜냐하면 우리는 Dog에 '1'의 실례가 있는데 그 키는 pets이기 때문이다.한편, ID 2의
Pet을 조회하면 다음과 같습니다.{
pet(id: "2"){
__typename,
...on Dog {
id
name
}
...on Cat {
id
name
age
}
}
}
우리는 다음과 같은 것을 얻었다.{
"data": {
"pet": {
"__typename": "Cat",
"id": "1",
"name": "Jane",
"age": 11
}
}
}
왜냐하면 우리는 Cat의 실례가 '2'의 가운데 키가 pets의 대상이기 때문이다.결론
우리는
GraphQLObjectType 구조 함수 생성 형식을 사용하여 대상 유형을 만들 수 있습니다.연합 유형을 만들려면
GraphQLUnionType을 사용할 수 있습니다. 그리고 대상의 유형을 검사하고 정확한 유형을 되돌려 resolveType 방법의 유형을 분석해야 합니다.우리는 내연 세션을 사용하여 연합 유형을 조회할 수 있으며,
__typename을 사용하여 이 유형을 검사할 수 있다.
Reference
이 문제에 관하여(GraphQL 패키지 구성 유형 사용), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/aumayeung/constructing-types-with-the-graphql-package-16jj텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)