craftcms / element-api

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

EVENT_BEFORE_SEND_DATA event not working #165

Closed mofman closed 2 years ago

mofman commented 2 years ago

Description

When listening for EVENT_BEFORE_SEND_DATA event, no data is being passed to data property.

Steps to reproduce

Event::on(\craft\elementapi\controllers\DefaultController::class, \craft\elementapi\controllers\DefaultController::EVENT_BEFORE_SEND_DATA, function(\craft\elementapi\DataEvent $e) {
    $logFile    = Craft::getAlias('@storage/logs/test.log');
    $logDetails = date('Y-m-d H:i:s') ."\n". print_r($e, true) ."\n\n";
    \craft\helpers\FileHelper::writeToFile($logFile, $logDetails, ['append' => true]);
});

Response:

craft\elementapi\DataEvent Object
(
    [data] => 
    [name] => beforeSendData
    [sender] => craft\elementapi\controllers\DefaultController Object
    .......
)

Additional info

mofman commented 2 years ago

Just to add onto this, the event is only fired when either the cache is disabled or when there is no cache. Shouldn't this fire regardless?

We're trying to use it to collect analytics on what people are searching for...

mofman commented 2 years ago

@angrybrad any possibility of getting this merged into v2 branch?

angrybrad commented 2 years ago

@mofman done https://github.com/craftcms/element-api/releases/tag/2.8.6

mofman commented 1 year ago
Event::on(\craft\elementapi\controllers\DefaultController::class, \craft\elementapi\controllers\DefaultController::EVENT_BEFORE_SEND_DATA, function(\craft\elementapi\DataEvent $e) {
        $file          = fopen(Craft::getAlias('@storage/logs/itineraries.csv'), 'a');
        $response      = $e->payload->toArray();
        $line          = [];
        $line['date']  = date('Y-m-d H:i:s');
        $line['total'] = $response['meta']['pagination']['total'];
        $line['query'] = $e->sender->request->getQueryStringWithoutPath();
        fputcsv($file, $line);
        fclose($file);
});

Adding the code I used to track queries going through element-api, may be of use to someone.

@angrybrad Is there any way to always fire the event even if it is already cached?

olivierbon commented 1 year ago

@mofman Right now, there isn't as the onBeforeSendData event does not get triggered when the cache is warm (see here)

yoannisj commented 10 months ago

@mofman this probably comes too late but an idea to track all requests (with info about data returned) would be to listen to incoming web requests (e.g. \craft\web\Application::EVENT_AFTER_REQUEST) check if the request goes to one of the element-api endpoints, and get the data from the element-api cache? This way you should be able to track calls even when the cache is warm no?