johannschopplich / cacao-kit-frontend

🍫 Best practice Nuxt and KQL starter for your headless Kirby CMS
https://cacao-kit.byjohann.dev
MIT License
30 stars 3 forks source link

Writing from the frontend to the backend #6

Closed antoine3000 closed 4 months ago

antoine3000 commented 4 months ago

Good morning,

Is it possible to write data from frontend to backend with this setup? If not, what would you suggest for saving data from a form?

Thanks, A

johannschopplich commented 4 months ago

Sure! As an example, let's upate the author field of a given page.

In your backend, create a plugin that provides an API route:

// site/plugins/yourplugin/index.php
<?php

use Kirby\Cms\App;

App::plugin('yourname/yourplugin', [
    'api' => require __DIR__ . '/extensions/api.php'
]);
// site/plugins/yourplugin/extensions/api.php
<?php

use JohannSchopplich\Headless\Api\Api;
use JohannSchopplich\Headless\Api\Middlewares;
use Kirby\Cms\App;

return [
    'routes' => function (App $kirby) {
        return [
            [
                'pattern' => 'yourplugin/updatePage',
                'method' => 'POST',
                // Disable auth for this route, because we use the bearer token middleware
                'auth' => false,
                'action' => Api::createHandler(
                    // Check if the request has a valid bearer token
                    [Middlewares::class, 'hasBearerToken'],
                    // Execute the action only if the bearer token is valid
                    function () use ($kirby) {
                        $body = $kirby->request()->body();
                        $id = $body->get('id');
                        $page = $kirby->page($id);

                        if (!$id || !$page) {
                            return Api::createResponse(404);
                        }

                        $kirby->impersonate('kirby', function () use ($page) {
                            $page->update([
                              'author' => 'Homer Simpson'
                            ]);
                          });

                        return Api::createResponse(201, [
                            'result' => 'ok'
                        ]);
                    }
                )
            ]
        ];
    }
];

In the frontend, we can use the $kirby composable (not documented yet...), which is a simple $fetch wrapper that will provide this same functionality as useKql: server proxy to hide your credentials.

const id = 'home'
const { result } = await $kirby('api/yourplugin/updatePage', {
  method: 'POST',
  body: {
    id,
  },
})

Of course, wrap this request in try/catch to make sure you catch any errors, for example, if the page can't be found.

Hope that helps!

antoine3000 commented 4 months ago

Fantastic, thank you! I'll try it now. And thanks again for the great starter kit, i love it.

antoine3000 commented 4 months ago

@johannschopplich It works like a charm, thanks again!