Laravel 5 또는 Lumen과 함께 Facebook GraphQL을 사용하세요. 이는 여기의 PHP 구현을 기반으로 합니다. GraphQL에 대한 자세한 내용은 React 블로그의 GraphQL 소개에서 확인하거나 GraphQL 사양을 읽어보세요. 이 작업은 진행 중입니다.
이 패키지는 Eloquent 모델(또는 기타 데이터 소스)과 호환됩니다. 아래 예를 참조하세요.
버전 1.0이 출시되었습니다. 이전 버전에서 업그레이드하는 경우 1.0으로 업그레이드를 선택하세요.
1- composer.json 의 Composer를 통해 패키지가 필요합니다.
{
"require" : {
"folklore/graphql" : " ~1.0.0 "
}
}2- Composer를 실행하여 새 요구 사항을 설치하거나 업데이트합니다.
$ composer install또는
$ composer update1- 구성 파일 게시
$ php artisan vendor:publish --provider= " FolkloreGraphQLServiceProvider "2- 구성 파일 검토
config/graphql.php
1- config/app.php 파일에 서비스 제공자를 추가합니다.
Folklore GraphQL ServiceProvider::class, 2- config/app.php 파일에 파사드를 추가하세요
' GraphQL ' => Folklore GraphQL Support Facades GraphQL::class,3- 구성 파일 게시
$ php artisan vendor:publish --provider= " FolkloreGraphQLServiceProvider "4- 구성 파일 검토
config/graphql.php
1- bootstrap/app.php 에서 서비스 제공자를 로드합니다.
$ app -> register ( Folklore GraphQL LumenServiceProvider::class); 2- Facade를 사용하려면 $app->withFacades(); bootstrap/app.php 에서
이 줄의 주석 처리를 제거하면 GraphQL 파사드가 활성화됩니다.
$ app -> withFacades ();3- 구성 파일 게시
$ php artisan graphql:publish 4- bootstrap/app.php 에 구성 파일 로드
중요 : 이 명령은 서비스 공급자를 등록하기 전에 실행되어야 합니다.
$ app -> configure ( ' graphql ' );
. . .
$ app -> register ( Folklore GraphQL LumenServiceProvider::class)5- 구성 파일 검토
config/graphql.php
버전 1.0부터 여러 스키마를 정의할 수 있습니다. 예를 들어 공개 엔드포인트와 인증이 필요한 다른 엔드포인트를 원하는 경우 여러 스키마를 갖는 것이 유용할 수 있습니다.
구성에서 여러 스키마를 정의할 수 있습니다.
' schema ' => ' default ' ,
' schemas ' => [
' default ' => [
' query ' => [
// 'users' = > 'AppGraphQLQueryUsersQuery'
],
' mutation ' => [
// 'updateUserEmail' = > 'AppGraphQLQueryUpdateUserEmailMutation'
]
],
' secret ' => [
' query ' => [
// 'users' = > 'AppGraphQLQueryUsersQuery'
],
' mutation ' => [
// 'updateUserEmail' = > 'AppGraphQLQueryUpdateUserEmailMutation'
]
]
]또는 Facade를 사용하여 스키마를 추가할 수 있습니다.
GraphQL:: addSchema ( ' secret ' , [
' query ' => [
' users ' => ' AppGraphQLQueryUsersQuery '
],
' mutation ' => [
' updateUserEmail ' => ' AppGraphQLQueryUpdateUserEmailMutation '
]
]);그런 다음 Facade를 사용하여 스키마를 빌드할 수 있습니다.
// Will return the default schema defined by 'schema' in the config
$ schema = GraphQL:: schema ();
// Will return the 'secret' schema
$ schema = GraphQL:: schema ( ' secret ' );
// Will build a new schema
$ schema = GraphQL:: schema ([
' query ' => [
// 'users' = > 'AppGraphQLQueryUsersQuery'
],
' mutation ' => [
// 'updateUserEmail' = > 'AppGraphQLQueryUpdateUserEmailMutation'
]
]);또는 특정 스키마에 대한 엔드포인트를 요청할 수 있습니다.
// Default schema
http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}
// Secret schema
http://homestead.app/graphql/secret?query=query+FetchUsers{users{id,email}}
먼저 유형을 만들어야 합니다.
namespace App GraphQL Type ;
use GraphQL Type Definition Type ;
use Folklore GraphQL Support Type as GraphQLType ;
class UserType extends GraphQLType
{
protected $ attributes = [
' name ' => ' User ' ,
' description ' => ' A user '
];
/ *
* Uncomment following line to make the type input object .
* http : // graphql . org / learn / schema / #input-types
* /
// protected $ inputObject = true ;
public function fields ()
{
return [
' id ' => [
' type ' => Type:: nonNull (Type:: string ()),
' description ' => ' The id of the user '
],
' email ' => [
' type ' => Type:: string (),
' description ' => ' The email of user '
]
];
}
// If you want to resolve the field yourself , you can declare a method
// with the following format resolve [ FIELD_NAME ] Field ()
protected function resolveEmailField ( $ root , $ args )
{
return strtolower ( $ root -> email );
}
} config/graphql.php 구성 파일에 유형을 추가하세요.
' types ' => [
' User ' => ' AppGraphQLTypeUserType '
] 예를 들어 서비스 제공자에서 GraphQL Facade를 사용하여 유형을 추가할 수도 있습니다.
GraphQL:: addType ( ' AppGraphQLTypeUserType ' , ' User ' );그런 다음 이 유형(또는 목록)을 반환하는 쿼리를 정의해야 합니다. 해결 메서드에서 사용할 수 있는 인수를 지정할 수도 있습니다.
namespace App GraphQL Query ;
use GraphQL ;
use GraphQL Type Definition Type ;
use Folklore GraphQL Support Query ;
use App User ;
class UsersQuery extends Query
{
protected $ attributes = [
' name ' => ' users '
];
public function type ()
{
return Type:: listOf (GraphQL:: type ( ' User ' ));
}
public function args ()
{
return [
' id ' => [ ' name ' => ' id ' , ' type ' => Type:: string ()],
' email ' => [ ' name ' => ' email ' , ' type ' => Type:: string ()]
];
}
public function resolve ( $ root , $ args )
{
if ( isset ( $ args [ ' id ' ])) {
return User:: where ( ' id ' , $ args [ ' id ' ])-> get ();
} else if ( isset ( $ args [ ' email ' ])) {
return User:: where ( ' email ' , $ args [ ' email ' ])-> get ();
} else {
return User:: all ();
}
}
} config/graphql.php 구성 파일에 쿼리를 추가합니다.
' schemas ' => [
' default ' => [
' query ' => [
' users ' => ' AppGraphQLQueryUsersQuery '
],
// ...
]
] 그리고 그게 다입니다. url /graphql (또는 구성에서 선택한 항목)에 대한 요청을 통해 GraphQL을 쿼리할 수 있어야 합니다. 다음 query 입력으로 GET 요청을 시도해 보세요.
query FetchUsers {
users {
id
email
}
}
예를 들어, 농가를 사용하는 경우:
http://homestead.app/graphql?query=query+FetchUsers{users{id,email}}
변형은 다른 쿼리와 마찬가지로 인수(변형을 수행하는 데 사용됨)를 받아들이고 특정 유형의 객체를 반환합니다.
예를 들어 사용자의 비밀번호를 업데이트하는 변형입니다. 먼저 Mutation을 정의해야 합니다.
namespace App GraphQL Mutation ;
use GraphQL ;
use GraphQL Type Definition Type ;
use Folklore GraphQL Support Mutation ;
use App User ;
class UpdateUserPasswordMutation extends Mutation
{
protected $ attributes = [
' name ' => ' updateUserPassword '
];
public function type ()
{
return GraphQL:: type ( ' User ' );
}
public function args ()
{
return [
' id ' => [ ' name ' => ' id ' , ' type ' => Type:: nonNull (Type:: string ())],
' password ' => [ ' name ' => ' password ' , ' type ' => Type:: nonNull (Type:: string ())]
];
}
public function resolve ( $ root , $ args )
{
$ user = User:: find ( $ args [ ' id ' ]);
if (! $ user ) {
return null ;
}
$ user -> password = bcrypt ( $ args [ ' password ' ]);
$ user -> save ();
return $ user ;
}
} resolve 메소드에서 볼 수 있듯이 인수를 사용하여 모델을 업데이트하고 반환합니다.
그런 다음 config/graphql.php 구성 파일에 변형을 추가합니다.
' schema ' => [
' default ' => [
' mutation ' => [
' updateUserPassword ' => ' AppGraphQLMutationUpdateUserPasswordMutation '
],
// ...
]
]그러면 엔드포인트에서 다음 쿼리를 사용하여 변형을 수행할 수 있습니다.
mutation users {
updateUserPassword(id: "1", password: "newpassword") {
id
email
}
}
농가를 사용하는 경우:
http://homestead.app/graphql?query=mutation+users{updateUserPassword(id: "1", password: "newpassword"){id,email}}
Mutation에 유효성 검사 규칙을 추가하는 것이 가능합니다. laravel Validator 사용하여 args 에 대한 유효성 검사를 수행합니다.
변형을 생성할 때 다음을 수행하여 적용되는 유효성 검사 규칙을 정의하는 메서드를 추가할 수 있습니다.
namespace App GraphQL Mutation ;
use GraphQL ;
use GraphQL Type Definition Type ;
use Folklore GraphQL Support Mutation ;
use App User ;
class UpdateUserEmailMutation extends Mutation
{
protected $ attributes = [
' name ' => ' UpdateUserEmail '
];
public function type ()
{
return GraphQL:: type ( ' User ' );
}
public function args ()
{
return [
' id ' => [ ' name ' => ' id ' , ' type ' => Type:: string ()],
' email ' => [ ' name ' => ' email ' , ' type ' => Type:: string ()]
];
}
public function rules ()
{
return [
' id ' => [ ' required ' ],
' email ' => [ ' required ' , ' email ' ]
];
}
public function resolve ( $ root , $ args )
{
$ user = User:: find ( $ args [ ' id ' ]);
if (! $ user ) {
return null ;
}
$ user -> email = $ args [ ' email ' ];
$ user -> save ();
return $ user ;
}
}또는 각 인수로 규칙을 정의할 수 있습니다.
class UpdateUserEmailMutation extends Mutation
{
// ...
public function args ()
{
return [
' id ' => [
' name ' => ' id ' ,
' type ' => Type:: string (),
' rules ' => [ ' required ' ]
],
' email ' => [
' name ' => ' email ' ,
' type ' => Type:: string (),
' rules ' => [ ' required ' , ' email ' ]
]
];
}
// ...
} 변형을 실행하면 유효성 검사 오류가 반환됩니다. GraphQL 사양은 오류에 대한 특정 형식을 정의하므로 유효성 검사 오류 메시지는 추가 validation 속성으로 오류 개체에 추가됩니다. 유효성 검사 오류를 찾으려면 'validation' 과 같은 message 로 오류를 확인해야 합니다. 그런 다음 validation 속성에는 Laravel 유효성 검사기가 반환한 일반적인 오류 메시지가 포함됩니다.
{
"data" : {
"updateUserEmail" : null
},
"errors" : [
{
"message" : " validation " ,
"locations" : [
{
"line" : 1 ,
"column" : 20
}
],
"validation" : {
"email" : [
" The email is invalid. "
]
}
}
]
}