Hi all.
I am trying to write a plugin that backups the entire content
folder as a .zip-file upon the click of a button in the panel. I am fairly new to some of these concepts and it’s more of a learning exercise for me, so please bear with me.
In my plugin’s index.php
I have registered a route to create-backup
. I am triggering that route through XHR from the Vue component. Everything works and the backups
folder and backup.zip
are successfully created.
I am, however, getting a 404 – Not Found
error in the console — which I guess makes sense, given that there is nothing actually there. It doesn’t break the script but I am wondering if there is a more elegant solution to this?
In a second step, I would like to register the created backups to a backups array which can then be used to display them on the page.
This works find after I click the Create Backup
button but I am a little on over my head when it comes to making that data persistent. Is there a way to send the backups
array to the pages .txt
and auto-save it after the click of the backup
button?
Here is my (slightly abbreviated) code so far:
index.php
Kirby::plugin("jonasfeige/backup", [
"routes" => [
[
"pattern" => "create-backup",
"action" => function () {
$kirby = Kirby::instance();
$backup_folder = $kirby->root("index") . "/backups";
$content_folder = $kirby->root("index") . "/content";
$content = Dir::read($content_folder);
$date = $_POST["date"];
$zip_name = "backup_" . $date . ".zip";
Dir::make($backup_folder);
// ...
// Create Zip
},
"method" => "POST"
]
],
"fields" => [
"backup" => [
"props" => [
"backups" => function ($backups) {
return $backups;
}
]
]
]
]);
Vue component
<template>
<k-field :label="label">
<k-button icon="check" @click="createBackup">Create Backup</k-button>
<k-box class="backup__entry" v-for="backup in backups" :key="backup.id">{{ backup }}</k-box>
</k-field>
</template>
<script>
import moment from 'moment'
export default {
data() {
return {
pathArr: location.pathname.split('/')
}
},
props: {
label: String,
backups: {
type: Array,
default: () => []
}
},
methods: {
createBackup() {
const self = this
const zipRoute = document.location.origin + '/' + this.pathName + '/create-backup'
const date = moment().format('YY-MM-DD_HH-mm-ss')
const params = `date=${date}`
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 || this.readyState == 4 && this.status == 404) {
self.backups.push('backup_' + date)
self.$emit('input', event)
}
}
xhttp.open('POST', zipRoute, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(params);
}
},
computed: {
pathName(){
return this.pathArr.length > 1 ? `/${this.pathArr[1]}/${this.pathArr[2]}` : '/'
}
}
}
</script>