Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Apiplatform Typescript Generator Bundle Laravel Package

a5sys/apiplatform-typescript-generator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation Add the bundle via Composer (if available in a public repo or manually cloned):

    composer require a5sys/apiplatform-typescript-generator-bundle
    

    If not published, clone the repo and require it locally:

    composer require [email protected]:A5sys/ApiPlatformTypescriptGeneratorBundle.git
    
  2. Enable the Bundle Register the bundle in config/bundles.php:

    return [
        // ...
        A5sys\ApiPlatformTypescriptGeneratorBundle\ApiPlatformTypescriptGeneratorBundle::class => ['all' => true],
    ];
    
  3. Configure the Generator Publish the default config (if available) and adjust in config/packages/a5sys_apiplatform_typescript_generator.yaml:

    php bin/console config:dump-reference | grep a5sys_apiplatform_typescript_generator
    

    Example minimal config:

    a5sys_apiplatform_typescript_generator:
        output_dir: '%kernel.project_dir%/client/src/generated'
        format: 'typescript'
        include: ['App\Entity']
        exclude: []
    
  4. First Use Case: Generate API Types Run the generator command to scaffold TypeScript interfaces/models:

    php bin/console a5sys:apiplatform:generate
    

    Verify output in client/src/generated/ (adjust output_dir as needed).


Implementation Patterns

Workflows

  1. Integrate with API Platform Resources Ensure your API Platform resources (e.g., src/Entity/Book.php) are annotated with @ApiResource:

    use ApiPlatform\Core\Annotation\ApiResource;
    
    #[ApiResource]
    class Book {}
    

    The generator will pick up these entities automatically (based on include/exclude config).

  2. Customize Output Structure Use Twig templates to modify generated files. Override the default template path:

    a5sys_apiplatform_typescript_generator:
        template: '%kernel.project_dir%/templates/typescript/generated.twig'
    

    Example template snippet:

    {# client/src/generated/Book.ts #}
    export interface Book {
        {# Loop through properties #}
        {% for property, type in properties %}
        {{ property }}: {{ type }};
        {% endfor %}
    }
    
  3. Incremental Generation Use --force to overwrite existing files or --dry-run to preview changes:

    php bin/console a5sys:apiplatform:generate --force
    php bin/console a5sys:apiplatform:generate --dry-run
    
  4. Hook into Build Process Add the command to your composer.json scripts for CI/CD:

    "scripts": {
        "post-autoload-dump": [
            "php bin/console a5sys:apiplatform:generate --force"
        ]
    }
    

Integration Tips

  • Frontend Framework Compatibility Generate types for React/Vue by extending the output template to include hooks/lifecycle methods:

    export interface BookState {
        data: Book | null;
        loading: boolean;
        error: string | null;
    }
    
  • API Platform Extensions For custom serializers/validators, ensure the generator accounts for them by extending the metadata parser:

    a5sys_apiplatform_typescript_generator:
        metadata_parser: 'App\Service\CustomMetadataParser'
    
  • Monorepo Setups Use symlinks or absolute paths in output_dir to share generated types across frontend/backend repos.


Gotchas and Tips

Pitfalls

  1. POC Limitations

    • No Official Docs: Assume undocumented behavior (e.g., template variables, config keys).
    • Breaking Changes: The bundle is a draft; expect API shifts between minor versions.
    • Dependency Risks: No dependents mean untested edge cases (e.g., nested collections, circular references).
  2. Configuration Quirks

    • Entity Filtering: The include/exclude arrays use class names as strings (e.g., ['App\Entity\Book']), not objects.
    • Output Overwrites: By default, the generator appends to files. Use --force to replace them.
  3. Debugging

    • Dry Runs: Always test with --dry-run before committing:
      php bin/console a5sys:apiplatform:generate --dry-run -v
      
    • Template Errors: Check the output_dir for partial files if the command fails silently.
    • Metadata Issues: If types are missing, verify:
      • Entities are loaded by the API Platform metadata system.
      • No exclude rules are blocking them.

Extension Points

  1. Custom Metadata Parsing Override the default parser to handle custom attributes or logic:

    // src/Service/CustomMetadataParser.php
    namespace App\Service;
    
    use A5sys\ApiPlatformTypescriptGeneratorBundle\Parser\MetadataParserInterface;
    
    class CustomMetadataParser implements MetadataParserInterface {
        public function parse(object $entity): array {
            // Add custom logic (e.g., for @Groups from ApiPlatform\Metadata\ApiResource)
            return [
                'properties' => [
                    'id' => 'number',
                    // ...
                ],
            ];
        }
    }
    

    Register it in config:

    a5sys_apiplatform_typescript_generator:
        metadata_parser: 'App\Service\CustomMetadataParser'
    
  2. Post-Generation Hooks Use Symfony’s event system to modify files after generation. Example listener:

    // src/EventListener/GenerateTypesListener.php
    namespace App\EventListener;
    
    use A5sys\ApiPlatformTypescriptGeneratorBundle\Event\TypesGeneratedEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class GenerateTypesListener implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [
                TypesGeneratedEvent::class => 'onTypesGenerated',
            ];
        }
    
        public function onTypesGenerated(TypesGeneratedEvent $event) {
            $files = $event->getGeneratedFiles();
            foreach ($files as $path => $content) {
                // Modify content (e.g., add imports)
                $files[$path] = "import { BaseEntity } from './BaseEntity';\n" . $content;
            }
            $event->setGeneratedFiles($files);
        }
    }
    
  3. Handling Complex Types For relationships or collections, extend the template to generate nested interfaces:

    {# For a Book with Author relationship #}
    export interface Book {
        title: string;
        author: Author; {# Nested interface #}
    }
    
    export interface Author {
        name: string;
    }
    

    Ensure your metadata_parser resolves these relationships correctly.

Pro Tips

  • Version Pinning: Lock the bundle version in composer.json to avoid unexpected updates:
    "require": {
        "a5sys/apiplatform-typescript-generator-bundle": "dev-main"
    }
    
  • CI/CD Safety: Add a step to validate generated files (e.g., TypeScript compilation) in your pipeline.
  • Fallback for Missing Fields: Use default values in templates to avoid runtime errors:
    export interface Book {
        {# Fallback to 'any' if type is unknown #}
        {% for property, type in properties|default({}) %}
        {{ property }}: {{ type|default('any') }};
        {% endfor %}
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
gmostafa/php-graphql-client
xeviant/paystack
snowsoft/faker
meditationsteps/blogetc
animalyoung/laravel-influxdb
onix-solutions/sms-telera
lonely-lights/prosetta
oxygen/data
oxygen/core
jengo/base
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log