-
Notifications
You must be signed in to change notification settings - Fork 24
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feat user backup #64
Open
dubisdev
wants to merge
9
commits into
RizkyRajitha:dev
Choose a base branch
from
dubisdev:feat-user-backup
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feat user backup #64
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
1dcf146
add api endpoint
dubisdev 7dd44be
add component
dubisdev 7138007
fix: reload when data is restored
dubisdev 4894367
fix: layout and toast error
dubisdev 4c12641
chore: add confirmation previous to restore
dubisdev 7023955
toast error when file is corrupted
dubisdev 17afb75
tests: add backupFunction tests
dubisdev 7586d13
chore: move middleware to common handler function
dubisdev 52e36cb
fix: backupData function
dubisdev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
const path = require("path"); | ||
const { default: Prisma } = require("../db/dbconprisma"); | ||
|
||
require("dotenv").config({ | ||
path: path.join(__dirname, "../", ".env"), | ||
}); | ||
|
||
const { | ||
restoreBackupData, | ||
getPageDatawLinkAndSocialData, | ||
} = require("../lib/dbfuncprisma"); | ||
describe("Test backup function", () => { | ||
beforeAll(async () => { | ||
await Prisma.pagedata.deleteMany(); | ||
await Prisma.socialdata.deleteMany(); | ||
await Prisma.linkdata.deleteMany(); | ||
await Prisma.pagedata.create({ | ||
data: { | ||
id: 1, | ||
handlerText: "test", | ||
avatarUrl: "", | ||
avatarBorderColor: "#ffffff", | ||
bgColor: "#7ea2ff", | ||
accentColor: "#bdd7ff", | ||
handlerFontSize: "20", | ||
handlerFontColor: "#ffffff", | ||
avatarwidth: "50", | ||
footerBgColor: "#7ea2ff", | ||
footerTextSize: "12", | ||
footerText: "Test footer", | ||
footerTextColor: "#ffffff", | ||
handlerDescription: "Test description", | ||
handlerDescriptionFontColor: "#ffffff", | ||
linktreeWidth: "320", | ||
linkdata: { | ||
create: { | ||
bgColor: "#2C6BED", | ||
textColor: "#ffffff", | ||
displayText: "Welcome to Linkin", | ||
iconClass: "fas fa-link", | ||
linkUrl: "/~https://github.com/RizkyRajitha/linkin", | ||
}, | ||
}, | ||
socialdata: { | ||
create: { | ||
iconClass: "fab fa-github", | ||
linkUrl: "/~https://github.com/RizkyRajitha/linkin", | ||
bgColor: "#2C6BED", | ||
borderRadius: "5", | ||
}, | ||
}, | ||
}, | ||
}); | ||
}); | ||
|
||
beforeEach(() => { | ||
jest.spyOn(console, "log").mockImplementation(() => {}); | ||
}); | ||
|
||
afterAll(async () => { | ||
await Prisma.$disconnect(); | ||
}); | ||
|
||
test("fails when no data provided", async () => { | ||
await expect(restoreBackupData).rejects.toThrow("no data to backup"); | ||
}); | ||
|
||
test("backups correctly with correct info", async () => { | ||
const dataToBackup = { | ||
pageData: { | ||
id: 1, | ||
handlerText: "Test Backup", | ||
}, | ||
socialData: [], | ||
linkData: [], | ||
}; | ||
await restoreBackupData(dataToBackup); | ||
let dbInfo = await getPageDatawLinkAndSocialData(); | ||
|
||
for (let n in dataToBackup.pageData) { | ||
expect(dataToBackup.pageData[n]).toBe(dbInfo.pageData[n]); | ||
} | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
import { toast } from "react-toastify"; | ||
import Swal from "sweetalert2"; | ||
|
||
const BackupComponent = () => { | ||
const endpoint = | ||
process.env.NODE_ENV === "production" ? `` : "http://localhost:3000"; | ||
|
||
const getBackup = async () => { | ||
try { | ||
let res = await fetch(`${endpoint}/api/user/backup`).then((res) => | ||
res.json() | ||
); | ||
let data = JSON.stringify(res, undefined, 2); | ||
let blob = new Blob([data], { type: "application/json" }); | ||
|
||
const url = window.URL.createObjectURL(blob); | ||
const a = document.createElement("a"); | ||
a.style.display = "none"; | ||
a.href = url; | ||
|
||
// filename = linkin-backup-date.json | ||
let filename = `linkin-backup-${new Date() | ||
.toISOString() | ||
.slice(0, 16) | ||
.replace(":", "-")}.json`; | ||
a.download = filename; // set filename | ||
document.body.appendChild(a); | ||
a.click(); | ||
a.remove(); | ||
window.URL.revokeObjectURL(url); // avoid memory leaks | ||
} catch (error) { | ||
toast.error(`${error.message}`, { autoClose: 10000 }); | ||
} | ||
}; | ||
|
||
const handleBackup = async (event) => { | ||
event.preventDefault(); | ||
|
||
let file = document.getElementById("backup").files[0]; | ||
if (!file) return toast.error(`No file selected`, { autoClose: 5000 }); | ||
|
||
let confirm = await Swal.fire({ | ||
title: "Restore Data", | ||
text: "You won't be able to revert this!", | ||
icon: "warning", | ||
showCancelButton: true, | ||
confirmButtonColor: "#3085d6", | ||
cancelButtonColor: "#d33", | ||
confirmButtonText: "Restore data", | ||
}); | ||
|
||
if (!confirm.isConfirmed) return; | ||
|
||
let fr = new FileReader(); | ||
|
||
fr.onload = async function () { | ||
const dataJson = JSON.parse(fr.result); | ||
|
||
await fetch(`${endpoint}/api/user/backup`, { | ||
headers: { | ||
Accept: "application/json", | ||
"Content-Type": "application/json", | ||
}, | ||
method: "POST", | ||
body: JSON.stringify(dataJson), | ||
}) | ||
.then(async (res) => { | ||
console.log(res); | ||
if (!res.ok) throw Error((await res.json()).message); | ||
location.reload(); | ||
}) // reload for getting restored page data | ||
.catch((err) => { | ||
toast.error(`${err.message}`, { autoClose: 10000 }); | ||
toast.error(`File may be corrupted`, { autoClose: 10000 }); | ||
}); | ||
}; | ||
|
||
fr.readAsText(file); | ||
}; | ||
|
||
return ( | ||
<> | ||
<h3>Backup and Restore data</h3> | ||
<div className="mb-3 form-control"> | ||
<h5>Backup</h5> | ||
<button | ||
className={`btn btn-secondary d-inline mb-3`} | ||
onClick={getBackup} | ||
> | ||
Download Backup | ||
</button> | ||
<form> | ||
<label htmlFor="backup"> | ||
<h5>Restore data from file</h5> | ||
</label> | ||
<input | ||
type="file" | ||
accept="application/json" | ||
className="form-control mb-2" | ||
id="backup" | ||
/> | ||
<button | ||
type="submit" | ||
className="btn btn-secondary" | ||
onClick={handleBackup} | ||
> | ||
Restore Data | ||
</button> | ||
</form> | ||
</div> | ||
</> | ||
); | ||
}; | ||
|
||
export default BackupComponent; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { jwtAuth, use } from "../../../middleware/middleware"; | ||
import { | ||
getPageDatawLinkAndSocialData, | ||
restoreBackupData, | ||
} from "../../../lib/dbfuncprisma"; | ||
|
||
// endpoint for download and restore backups | ||
async function handler(req, res) { | ||
// Run the middleware | ||
await use(req, res, jwtAuth).catch((error) => { | ||
console.log(error.message); | ||
res.status(500).json({ success: false, message: error.message }); | ||
}); | ||
|
||
switch (req.method) { | ||
case "GET": | ||
return await get(req, res); | ||
case "POST": | ||
return await post(req, res); | ||
default: | ||
res.status(400).send("method not allowed"); | ||
return; | ||
} | ||
} | ||
|
||
async function get(req, res) { | ||
try { | ||
let data = await getPageDatawLinkAndSocialData(); | ||
|
||
res.json({ | ||
...data, | ||
linkin_version: process.env.NEXT_PUBLIC_VERSION || "", | ||
}); | ||
} catch (error) { | ||
console.log(error.message); | ||
|
||
res.status(500).json({ success: false, message: error.message }); | ||
} | ||
} | ||
|
||
async function post(req, res) { | ||
try { | ||
let { linkin_version, ...data } = req.body; | ||
|
||
await restoreBackupData(data); | ||
|
||
res.json({ success: true }); | ||
} catch (error) { | ||
console.log(error.message); | ||
res.status(400).json({ success: false, message: error.message }); | ||
} | ||
} | ||
|
||
export default handler; |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
use middleware here to avoid duplicates
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed in 7586d13