laravel-restype/laravel-restype

0.1.1 2023-05-01 17:13 UTC

This package is auto-updated.

Last update: 2024-04-30 00:45:54 UTC


README

This project has 2 components:

Warning ! Beta software ! please don't use this in production yet !

What is this ?

I saw the tRPC project and I wanted something similar, but for my existing Laravel projects.

After a quick google search I found the awesome project spatie/typescript-transformer, however the integration with laravel is very barebones, serving as a building block.

This project helps you generate TypeScript definitions for your entire existing laravel REST api. After the definition is generated, you can import it in your frontend, or download it into your react-native project.

Instalation

composer require laravel-restype/laravel-restype:"*"

Publish config

php artisan vendor:publish --tag="laravel-restype-config"

Usage

  1. First, let's enable automatic discovery for all your routes. In your routes/api.php file, add this empty class:
use Spatie\TypeScriptTransformer\Attributes\TypeScript;

#[TypeScript]
class ApiRoutes
{
}

Route::get('/hello-world', [HomeController::class, 'hello_world']);

// TODO: not the best solution. make a custom transformer for this one with a prefix parameter

  1. Then, add Route definitions for every controller method that coresponds to a route.
use LaravelRESType\Attributes\RouteTypeScriptType;
use Spatie\TypeScriptTransformer\Attributes\TypeScript;

#[TypeScript]
class HomeController extends Controller
{
    #[
        RouteTypeScriptType([
            'responses' => [
                [
                    'hello' => '"world"',
                    'message' => 'string',
                ],
            ],
        ])
    ]
    public $hello_world;
    public function hello_world(Request $request)
    {
        return [
            'hello' => 'world',
            'message' => 'Make the web a better place !',
        ];
    }
}

Note: a current limitation is that we can't generate typescript definitions for class methods, instead we have to add an empty property with the same name as the method (public $hello_world).

  1. Generate your new typescript definition with:
php artisan typescript:transform

The default destination is: /public/types/generated.ts

  1. Install our client typescript package in your frontend project to use your new definitions.

Follow the steps from the client package documentation.

Example project

git clone https://github.com/laravel-restype/laravel-restype
cd laravel-restype/example
docker compose up -d
docker-compose exec php su app -c 'cd example; composer install'
docker-compose exec php su app -c 'cd example; cp .env.example .env; php artisan key:generate'

Roadmap:

Support url parameters (eg. /post/{id})
Support file type, convert json body to FormData

Changelog:

v0.1.1 - 2023-05-01

  • Patch - fixed method name generation for routes with params

v0.1 - 2023-01-07

  • First version