Laravel Lumen GraphQL Server for React Relay Modern

Having Laravel´s Lumen to work as a GraphQL Server able to provide feeds to client applications for Relay Modern its been a beautiful jurney, and i´ll like to share with the world on this publication.

Laravel its Magic, and this is a fact, thanks to its nature we able to do things like this, in this example all work its done thanks to a recently released v2 of an excellent library known as LightHouse, you can find documentation on nuwave/lighthouse, this library it´s in charge some Magic.

On its core uses another library, lets say Lighthouse its a Laravel Wrapper with supercharged powers, on top of webonyx/graphql-php, the real GraphQL implementation under PHP.

As a result of this implementation you able to access and download resuling proyect implementation on this GitHub Repository:

kikoseijo/lumen-lighthouse-graphql

The Jurney starts

Maybe i have missed some steps, but main logic its here, as you having the repository you can get from there whats not documented here.

Steps to reproduce

Fresh install of Lumen, and initial packages requirements its done on the following bash commands:

lumen new lumen-lighthouse-graphql
cd lumen-lighthouse-graphql
composer update
composer require nuwave/lighthouse
cp .env.example .env

setup your configuration folders, and lighthouse defaults folders needed if you are going to implement some queries, mutactions, etc…

mkdir config && mkdir app/Models && mkdir app/GraphQL && mkdir app/GraphQL/Mutations && mkdir app/GraphQL/Queries && mkdir app/GraphQL/Scalars && mkdir app/GraphQL/Directives
cp vendor/nuwave/lighthouse/config/config.php config/lighthouse.php

Helping Lumen acknowledge regarding Lighthouse:

$app->withFacades();
$app->withEloquent();
$app->configure('lighthouse');
...
$app->register(Nuwave\Lighthouse\Providers\LighthouseServiceProvider::class);

Add klaravel (Optional)

composer require ksoft/klaravel
cp vendor/ksoft/klaravel/stubs/config/ksoft.php config/ksoft.php
$app->configure('ksoft');

Laravel Passport

Im using a wrapper to be able to have Passport fully integrated on Laravel Lumen´s. For more info or extended usage:

https://github.com/dusterio/lumen-passport

composer require dusterio/lumen-passport
composer require appzcoder/lumen-routes-list
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Dusterio\LumenPassport\LumenPassport;
use Laravel\Passport\Passport;
use Carbon\Carbon;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        Passport::tokensExpireIn(Carbon::now()->addDays(15));
        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
        LumenPassport::tokensExpireIn(Carbon::now()->addYears(50), 2);
    }
}

Under AuthServiceProvider.php add this line in the boot method

// use Dusterio\LumenPassport\LumenPassport;
LumenPassport::routes($this->app, ['prefix' => 'v1/oauth']);

User model

use Laravel\Passport\HasApiTokens;

Enable Passport under Lumen:

$app->configure('auth');
...
$app->register(Laravel\Passport\PassportServiceProvider::class);
$app->register(Dusterio\LumenPassport\PassportServiceProvider::class);
// Optional if yo want to list your routes.
if ($app->environment() == 'local') {
    $app->register(Appzcoder\LumenRoutesList\RoutesCommandServiceProvider::class);
}

Now your are going to need the migrations:

php artisan make:migration create_users_table
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();

Seeder:

php artisan make:seeder UsersTableSeeder
if (!DB::table('users')->where('email', 'kiko@example.com')->first()) {
  DB::table('users')->insert([
    'name' => 'Kiko Seijo',
    'email' => 'kiko@example.com',
    'password' => app('hash')->make('secret'),
    // 'admin' => 1,
  ]);
}

Finish install Laravel Passport install with: This is the simplest way to setup a login method that Passport provides, there are many more https://laravel.com/docs/master/passport)

php artisan migrate --seed
php artisan passport:keys
php artisan passport:client --personal

Testing install:

mutation Login {
  login(username: "kiko@example.com", password: "secret") {
    user {
      id
      name
      email
    }
    token
  }
}

Should return:

{
  "data": {
    "login": {
      "user": {
        "id": "1",
        "name": "Kiko Seijo",
        "email": "kiko@example.com"
      },
      "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJS........your token"
    }
  }
}

Testing auth middleware from Viewer Query:

query ViewerQuery {
  viewer {
    id
    name
    email
  }
}

Add the headers to your query and adjust the token to the one you are getting from previous login:

{
  "Authorization": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJS........your token"
}

And you should get:

{
  "data": {
    "viewer": {
      "id": "1",
      "name": "Kiko Seijo",
      "email": "kiko@example.com"
    }
  }
}

GraphQL viewer Query with a Laravel Passport bearer token using Lighthouse auth middleware


Credits

Sunnyface.com, is a software development company from Málaga, Spain. We provide quality software based on the cloud for local & international companies, providing technology solutions with the most modern programming languages.

DevOps Web development
Custom App Development Mobile aplications
Social Apps and Startups Residents mobile application
Graphic designer Freelance senior programmer


Created by Kiko Seijo

Añade fuentes en iOS y Android con React-native – modo fáci

OS muestro la forma más sencilla para hacer que React-nativo sea capaz de instalar nuestras fuentes dentro de los proyectos de forma automática en aplicaciones iOS y Android.

  1. Primer paso

Elige una carpeta dentro de tu proyecto y copia ahí las fuentes, en nuestro caso
vamos a usar el directorio ./src/assets/fonts/

  1. Paso segundo

añade este trozo de código dentro de tu proyecto, en el archivo de configuración en la raíz del proyecto package.json:

  "rnpm": {
    "assets": ["./src/assets/fonts"]
  },

solo tienes que reemplazar tu directorio por ./src/assets/fonts.

  1. Paso final

corre el siguiente comando en tu terminal.

$ react-native link

Ahora, cada vez que quieras instalar una fuente en tu aplicación móvil, solo tienes que dejar caer la fuente y correr el último comando, i voailá ya puedes usar la fuente.

Pro Tip: Cada vez que corres el comando react-native link deberas recompliar el proyecto para que carge las nuevas librerías.

Configurar Atom para React-native y flow

1) Instalar Atom

Descarga la ultima versión de Atom desde la página oficial, Si usas mac y tienes Hombrew y Cas, puedes instalaro con el siguente comando:

$ brew cask install atom
2) Instalar Nuclide para Atom

Nuclide es un conjunto de herramientas de código abierto perfecto para trabajar con React.

Busca el plugin en el buscador de paquetes en las preferencias de atom o usando el siguente comando:

$ apm install nuclide
3) Configuramos nuclide

Abre Atom,
Busca “Ajustes > Paquetes instalados” o con el shortcut CMD + SHIFT + P y busca “paquetes instalados”:

Busca “Nuclide” y dale a “Ajustes”:

Busca la opción “Instalar paquetes recomendados al arrancar”, la activamos.

En la sección de “Nuclide-flow” activa la opción de usar flow de manera local en cada proyecto, esto requerira que instales flow-bin en cada proyecto de React, es lo que nos recomiendan hacer la gente de facebook.

4) Instalar Prettier para Atom

Prettier es tu mejor amigo, se encarga de hacer que tu código sea bonito y agradable de leer. Además es capaz de seguir una reglas que tu le marques en los archivos de configuración que tengas.
Para instalarlo desde la ventana de comandos:

$ apm install prettier-atom
5) Configuramos Prettier

Como en la sección anterior, buscamos el plugin instalado y nos vamos a editar sus preferencias:

Tenemos que asegurarnos que la opción de “Integrarse con ESlint” esté activada.

Reiniciamos Atom.

6) Listos!

Ya estamos lístos para trabajar como máquinas con un monton de herramientas creadas por los creadores de React.

— Así nos queda una instalación limpia con todos los plugins instalados —

Asi quedarían los paquetes instalados

Es hora de programar con mucho @flow.

Laravel lumen GraphQL Server for React Relay Moder

DEPRECATED

This project it’s no longer maintained in favor of v2 of nuwave/lighthouse.
You can find an example implementation for lumen on: https://github.com/kikoseijo/lumen-lighthouse-graphql

A GraphQL Server in PHP, its core its a fast micro-framework implementation (Lumen), and capable of delivering GraphQL (Relay) API responses.

React-Relay Modern, aka GraphQL v1.*

Visit repository

Introduction

On this Lumen version of a GraphQL server implementation you will be able to start coding right away a fully qualified GraphQL server with support for react-relay (Modern version).

With a Laravel heart, on his delighting micro-framework version (Lumen) and a help of a couple of other packages/plugins, we provide you with the basic server setup.

Why Lumen? and why PHP?

Why not my little Artisan? PHP limitations today for a GraphQL server are asynchronous calls, but this are problems PHP programmers been dealing with since the old days, the missing part are the GraphQL subscriptions, this can be resolved using lots of tools, like Redis or NodeJS.

PHP never been so optimized like it is today, its stable, fast and efficient. And Lumen?, because its a masterpiece, a lightweight version of Laravel, sharing same core and data structure. Perfect for building APIs.

For little Artisan like myself this is the perfect atmosphere to understand how things are achieved.

Who is this for?

People wanting to get hands dirty with GraphQL, to serve as a boilerplate to kick-off API projects, a knowledge of Laravel its recommended, at a installation level, not covered here.

Included features
  • Full CRUD example.
  • GraphQL Playground.
  • Database migrations.
  • GraphQl database schema generator and endpoint.
  • User authentication using Passport.
  • Ready to start after setup!
Client Web App

If you work with React we have published for you an application, there you can test all demo features, its a React + Relay based Web App. This is probably best way to have a full picture of what Relay its capable off, in my opinion, one of the best facebook´s open sourced contribution and React´s best friend. 💑

Visit the React Relay – WebApp client.