Browse Source

second

pull/1/head
david 3 years ago
parent
commit
5919a3a597
  1. 57
      apiHelper.js
  2. 12
      axios.js
  3. 8
      backupHelper.js
  4. 33
      index.js

57
apiHelper.js

@ -3,7 +3,7 @@ import { exportDatabaseValidation } from './validation.js';
import fs from 'fs';
import path from 'path';
const getBackups = async () => {
const getBackupsRequest = async () => {
try {
const { data } = await axiosWrapper({
method: 'get',
@ -16,12 +16,18 @@ const getBackups = async () => {
}
};
const exportDatabase = async (tag) => {
const exportDatabaseRequest = async (tag) => {
try {
const { value: validValue, error } = exportDatabaseValidation({ tag });
const timestampedTag = `${tag}_${Date.now()}`;
console.log(timestampedTag);
const { value: validValue, error } = exportDatabaseValidation({
tag: timestampedTag,
});
if (error) throw error?.details[0]?.message;
const { data } = await axiosWrapper({
const {
data: { export_path },
} = await axiosWrapper({
method: 'post',
url: '/backups/export/database',
payload: {
@ -38,14 +44,15 @@ const exportDatabase = async (tag) => {
templates: ['recipes.md'],
},
});
return data;
console.log(`Database backed up to ${export_path}`);
return true;
} catch (error) {
console.error(error);
return false;
}
};
const getFileToken = async (filename) => {
const getFileTokenRequest = async (filename) => {
try {
const { data } = await axiosWrapper({
method: 'get',
@ -58,9 +65,19 @@ const getFileToken = async (filename) => {
}
};
const downloadBackup = async (fileToken, fileName) => {
const downloadBackupRequest = async (fileToken, fileName) => {
try {
const target_path = path.resolve(`backups/${fileName}`);
const subFolder = new Date().toLocaleDateString('en-CA', {
year: 'numeric',
month: 'numeric',
});
const base_path = path.resolve('backups/');
const subfolderExists = fs.existsSync(`${base_path}/${subFolder}`);
if (!subfolderExists)
fs.mkdirSync(`${base_path}/${subFolder}`, { recursive: false }, (err) => {
if (err) throw err;
});
const target_path = `${base_path}/${subFolder}/${fileName}`;
const writer = fs.createWriteStream(target_path, 'binary');
const streamResponse = await axiosWrapper({
method: 'get',
@ -68,7 +85,7 @@ const downloadBackup = async (fileToken, fileName) => {
responseType: 'stream',
});
streamResponse.data.pipe(writer);
writer.on('finish', () => console.log(`Downloaded: ${fileName}`));
writer.on('finish', () => console.log(`Downloaded to ${target_path}`));
writer.on('error', () =>
console.error(`[ERROR] while dowloading ${fileName}`)
);
@ -79,4 +96,24 @@ const downloadBackup = async (fileToken, fileName) => {
}
};
export { getBackups, exportDatabase, getFileToken, downloadBackup };
const backupDeleteRequest = async (filename) => {
try {
await axiosWrapper({
method: 'delete',
url: `/backups/${filename}/delete`,
});
console.log(`Deleted ${filename} from mealie`);
return true;
} catch (error) {
console.error(error);
return false;
}
};
export {
getBackupsRequest,
exportDatabaseRequest,
getFileTokenRequest,
downloadBackupRequest,
backupDeleteRequest,
};

12
axios.js

@ -1,11 +1,19 @@
import axios from 'axios';
import { environmentVariableValidation } from './validation.js';
import dotenv from 'dotenv';
dotenv.config();
const { BASE_URL, TOKEN } = process.env;
const { value, error } = environmentVariableValidation({
baseUrl: BASE_URL,
access_token: TOKEN,
});
if (error) throw error?.details[0]?.message;
const config = {
baseURL: BASE_URL,
headers: { authorization: `Bearer ${TOKEN}` },
baseURL: value.baseUrl,
headers: { authorization: `Bearer ${value.access_token}` },
};
const axiosWrapper = async ({ method, url, payload, responseType }) => {

8
backupHelper.js

@ -12,4 +12,10 @@ const backupTimeDiff = (lastDate) => {
}
};
export { backupTimeDiff };
const backupsToDelete = (backupArray) => {
// get the list of backups to delete and return only the names
if (!backupArray) return [];
return backupArray.map(({ name }) => name);
};
export { backupTimeDiff, backupsToDelete };

33
index.js

@ -2,12 +2,13 @@ import dotenv from 'dotenv';
dotenv.config();
import { environmentVariableValidation } from './validation.js';
import {
getBackups,
exportDatabase,
getFileToken,
downloadBackup,
getBackupsRequest,
exportDatabaseRequest,
getFileTokenRequest,
downloadBackupRequest,
backupDeleteRequest,
} from './apiHelper.js';
import { backupTimeDiff } from './backupHelper.js';
import { backupTimeDiff, backupsToDelete } from './backupHelper.js';
const { value, error } = environmentVariableValidation({
baseUrl: process.env.BASE_URL,
@ -22,18 +23,22 @@ try {
}
const Main = async () => {
await new Promise((resolve) => setTimeout(resolve, 2000));
const backups = await getBackups();
const [lastBackup] = backups?.imports;
await new Promise((resolve) => setTimeout(resolve, 10000));
const backups = await getBackupsRequest();
const [lastBackup, ...rest] = backups?.imports;
const backupsToRemove = backupsToDelete(rest.splice(10));
const secondsDiff = backupTimeDiff(lastBackup?.date);
// TODO: actually make this timer like idk 1 day or something
if (secondsDiff >= 20) {
const { export_path } = await exportDatabase('mealieDb');
console.log(`database backed up: ${export_path}`);
const { fileToken } = await getFileToken(lastBackup?.name);
await downloadBackup(fileToken, lastBackup?.name);
if (secondsDiff >= 10) {
await exportDatabaseRequest('mealieDb');
const { fileToken } = await getFileTokenRequest(lastBackup?.name);
await downloadBackupRequest(fileToken, lastBackup?.name);
for (const file of backupsToRemove) {
await backupDeleteRequest(file);
await new Promise((resolve) => setTimeout(resolve, 300));
}
}
await Main(secondsDiff);
await Main();
};
Main();

Loading…
Cancel
Save