folkloreinc / laravel-graphql

Facebook GraphQL for Laravel 5. It supports Relay, eloquent models, validation and GraphiQL.
1.76k stars 234 forks source link

How to output paging data? #391

Open lilianjin opened 6 years ago

lilianjin commented 6 years ago

PHP

class ProductsQuery extends Query
{
    protected $attributes = [
        'name'  => 'Products Query'
    ];

    public function type()
    {
        return GraphQL::pagination(
                GraphQL::type('Product')
            );
    }

    public function resolve($root, $args)
    {
        return app(ProductRepositoryInterface::class)
            ->paginate([
                'per_page'  => 6
            ]);
    }
}

Query

{
    products {
      items {
        name
        str_id
        description
     }
   }
}
ikudosi commented 6 years ago

Hope this helps but here's an example of what I have.

class ModelWithPageInfo extends Folklore\GraphQL\Support\Type
{
    protected $attributes = [
        'name' => '',
        'description' => ''
    ];

    /**
     * @var string
     */
    protected $graphqlType;

    public function fields()
    {
        return [
            'pageInfo' => [
                'type' => GraphQL::type('PageInfo'),
                'resolve' => function ($root, $args) {
                    return [
                        'per_page' => $root->perPage(),
                        'current_page' => $root->currentPage(),
                        'total' => $root->total(),
                        'result_count' => $root->count()
                    ];
                }
            ],
            'hasMorePages' => [
                'type' => Type::boolean(),
                'resolve' => function ($root) {
                    return $root->hasMorePages();
                }
            ],
            'items' => [
                'type' => Type::listOf(GraphQL::type($this->graphqlType)),
                'resolve' => function ($root, $args) {
                    return $root->items();
                }
            ]
        ];
    }
}
class FoobarWithPageInfo extends ModelWithPageInfo
{
    protected $attributes = [
        'name' => 'FoobarWithPageInfo'
    ];

    protected $graphqlType = 'Foobar';
}
class PaginatedModelQuery extends Folklore\GraphQL\Support\Query
{
    public function type()
    {
        return GraphQL::type('ModelWithPageInfo ');
    }

    /**
     * @return array
     */
    public function args()
    {
        return ['name' => 'page', 'description' => 'The page', 'type' => Type::int()]);
    }

    /**
     * @return mixed
     */
    protected function resolve($root, $args, $context, ResolveInfo $info)
    {
        return Foobar::paginate($args['limit'] ?? 20, ['*'], 'page', $args['page'] ?? 1);
    }
}
lilianjin commented 6 years ago

@ikudosi Thank you, I have solved this problem.