Lighthouse: Custom non eloquent type

Created on 24 Mar 2019  路  2Comments  路  Source: nuwave/lighthouse

Maybe I just haven't wrapped my head around it enough, but I have a datasource (Phillips hue API) that I can pull data from, I would like to create a graphql type that represents this data, however I am unsure how to implement this as I cant use a model, any suggestions, thanks.

question

Most helpful comment

Look into how you can create a custom resolver here: https://lighthouse-php.com/master/the-basics/fields.html#subscribe-to-data

Without knowing anything about Phillips Hue you might do something similar to this:

type Query {
  devices: [Device!]!
}

type Device {
    id: ID!
    name: String!
}
<?php

namespace App\Queries

class Devices
{
    protected $hue;

    // Use Dependency Injection via the Laravel Container to construct
    // this class with an instance of your HueApi service class
    public function __construct(HueApi $hue)
    {
        $this->hue = $hue;
    }

    public function resolve($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): array
    {
        // Ensure you return data in a shape that matches the Type you promised
        // to return in your schema definition
        return array_map(
            function($device): array {
                return [
                    'id' => $device->getId(),
                    'name' => $device->getDeviceName()
                ];
            },
            $this->hue->fetchDeviceList()
        }
    }
}

All 2 comments

Look into how you can create a custom resolver here: https://lighthouse-php.com/master/the-basics/fields.html#subscribe-to-data

Without knowing anything about Phillips Hue you might do something similar to this:

type Query {
  devices: [Device!]!
}

type Device {
    id: ID!
    name: String!
}
<?php

namespace App\Queries

class Devices
{
    protected $hue;

    // Use Dependency Injection via the Laravel Container to construct
    // this class with an instance of your HueApi service class
    public function __construct(HueApi $hue)
    {
        $this->hue = $hue;
    }

    public function resolve($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): array
    {
        // Ensure you return data in a shape that matches the Type you promised
        // to return in your schema definition
        return array_map(
            function($device): array {
                return [
                    'id' => $device->getId(),
                    'name' => $device->getDeviceName()
                ];
            },
            $this->hue->fetchDeviceList()
        }
    }
}

Perfect, I'll look into it. Thanks for the customized explanation.

Was this page helpful?
0 / 5 - 0 ratings