craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 57 forks source link

Craft CLI exception when element api is configured #80

Closed thaoms closed 6 years ago

thaoms commented 6 years ago

I'm fetching some data before using the element api:

'criteria' => [
         'section' => 'productions',
         'limit' => 10,
    'search' => [
        'query' => 'title:' . Craft::$app->getRequest()->getParam('q'),
        'subLeft' => true,
        'subRight' => true
    ]
],

But when using the Craft cli with ./craft I get this error:

Exception 'yii\base\UnknownMethodException' with message 
'Calling unknown method: craft\console\Request::getParam()'

/vendor/yiisoft/yii2/base/Component.php:300

Not really sure where to post this issue.

angrybrad commented 6 years ago

Params in a querystring only exist in the context of a web browser/request, not at the console. If you don't want that code to run in the context of a console request, you can do something like:

'query' => !Craft::$app->getRequest()->getIsConsoleRequest() ? 'title:' . Craft::$app->getRequest()->getParam('q') : null,
brandonkelly commented 6 years ago

Rather than modify your query logic, you could leave that as-is, but place all of your endpoint config array inside an anonymous function. (See Dynamic URL Patterns and Endpoint Configurations.)

'endpoint-url-pattern' => function() {
    return [
        'criteria' => [
            'section' => 'productions',
            'limit' => 10,
            'search' => [
                'query' => 'title:' . Craft::$app->getRequest()->getParam('q'),
                'subLeft' => true,
                'subRight' => true,
            ],
        ],
        // ...
    ];
},

That way, your endpoint config will only be generated when the endpoint is actually requested, rather than on every web & console request.

carlcs commented 6 years ago

This seems to be a common problem, maybe you could add a note to the readme? Or have both example endpoints return a function.

brandonkelly commented 6 years ago

@carlcs Yeah good idea, now all endpoint config examples use a function.