3

I'm working on a Vue SPA (single page application) for a client and my ElementAPI config file has grown to be quite large. To make it easier to maintain I was looking for suggestions of how to have each endpoint in its own file.

Any feedback is appreciated!

1 Answers1

1

I had sometime to review the documentation in more depth; https://github.com/craftcms/element-api/tree/v1#transformer

An abbreviated example below. Note, I include all transformers in a /transformers directory within /config.

file - craft/config/elementapi.php

  return [
    'endpoints' => [
      // Home
      //
      'api/home' => function() {
        require craft()->path->getConfigPath().'transformers/home.php';
        return [
          'elementType' => ElementType::Entry,
          'criteria' => [
            'section' => 'homepage'
          ],
          'first' => true,
          'cache' => 'PT1M',
          'transformer' => new homeAPI(),
        ];
      },

      // About
      //
      'api/about' => function() {
        require craft()->path->getConfigPath().'transformers/about.php';
        return [
          'elementType' => ElementType::Entry,
          'criteria' => [
            'section' => 'about'
          ],
          'first' => true,
          'transformer' => new aboutAPI(),
        ];
      },

      // Remaining Endpoints...
      // 
    ]
  ];
?>

file - craft/config/transformers/home.php

<?php
  namespace Craft;
  require craft()->path->getPluginsPath().'elementapi/vendor/autoload.php';
  use League\Fractal\TransformerAbstract;

  class homeAPI extends TransformerAbstract {
    public function transform(EntryModel $entry) {

      $bodyBlocks = [];
      foreach ($entry->homepageContent as $block) {
        switch ($block->type->handle) {
          case 'gallery':

            $bodyBlocks[] = [
              'gallery' => [
                'thumbnails' => $thumbnails
              ]
            ];
          break;

          // Remaining Fields...
          //
        }
      }

      return [
        'id' => (integer) $entry->id,
        'title' => $entry->title,
        'content' => $bodyBlocks,
      ];
    }
  }