Skip to content

Commit

Permalink
Merge pull request #8 from cxumol/refactor
Browse files Browse the repository at this point in the history
Refactor: misc decoupling and comments
  • Loading branch information
cxumol authored Nov 17, 2023
2 parents 17360c5 + a13bc72 commit 823120b
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 167 deletions.
132 changes: 66 additions & 66 deletions src/lib/db.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,66 @@
const myheaders = {
Origin: window.location.origin,
'Content-Type': 'text/plain'
};

async function getDefaultData(){
const response = await fetch(`/data_default.json`);
if (!response.ok){
throw new Error(response);
}else{
return await response.json();
}
}

function dataKeysUpdate(template, toAlign){
for (const k of Object.keys(template)) {
if (!toAlign.hasOwnProperty(k)) {
console.log(`data field updated implicitly, updated key:${k}`);
toAlign[k] = template[k];
}
}
return toAlign;
}

class DB {
constructor(cf_workers, username){
this.cf_workers = cf_workers;
this.username = username;
this.needToken = null;
}
async getData() {
const defaultData = getDefaultData();
const response = await fetch(`https://${this.cf_workers}/get/${this.username}`, { headers: myheaders });
if (!response.ok) {
// use default data
return getDefaultData();
}
if (response.headers.get('x-need-token')) {
this.needToken = true;
console.log('A token is required to edit this page');
} else {
this.needToken = false;
}
const result = await response.json();
const cloudData = dataKeysUpdate(defaultData, result);
return cloudData;
}

async uploadData(myDataStr) {

const response = await fetch(`https://${this.cf_workers}/set/${this.username}`, {
headers: myheaders,
method: 'POST',
body: myDataStr
})
if (!response.ok) {
response.text().then((msg) => alert(`unsuccessful data uploading \nReason: ${msg}`));
return {uploadingState: 'bad'}
}
return {uploadingState: 'ok'};
}
}


export {DB};
const myheaders = {
Origin: window.location.origin,
'Content-Type': 'text/plain'
};

async function getDefaultData() {
const response = await fetch(`/data_default.json`);
if (!response.ok) {
throw new Error(response);
} else {
return await response.json();
}
}

function dataKeysUpdate(template, toAlign) {
for (const k of Object.keys(template)) {
if (!toAlign.hasOwnProperty(k)) {
console.log(`data field updated implicitly, updated key:${k}`);
toAlign[k] = template[k];
}
}
return toAlign;
}

class DB {
constructor(cf_workers, username) {
this.cf_workers = cf_workers;
this.username = username;
this.needToken = null;
}

async getData() {
const defaultData = getDefaultData();
const response = await fetch(`https://${this.cf_workers}/get/${this.username}`, {
headers: myheaders
});
if (!response.ok) {
// use default data
return getDefaultData();
}
if (response.headers.get('x-need-token')) {
this.needToken = true;
console.log('A token is required to edit this page');
} else {
this.needToken = false;
}
const result = await response.json();
const cloudData = dataKeysUpdate(defaultData, result);
return cloudData;
}

async uploadData(myDataStr) {
const response = await fetch(`https://${this.cf_workers}/set/${this.username}`, {
headers: myheaders,
method: 'POST',
body: myDataStr
});
if (!response.ok) {
response.text().then((msg) => alert(`unsuccessful data uploading \nReason: ${msg}`));
return { uploadingState: 'bad' };
}
return { uploadingState: 'ok' };
}
}

export { DB };
8 changes: 8 additions & 0 deletions src/lib/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
function newRandomID() {
let result = Math.random().toString(36).slice(-8);
while (result.length < 8) {
result = Math.random().toString(36).slice(-8);
}
return result;
}
export { newRandomID };
2 changes: 1 addition & 1 deletion src/routes/+page.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ export async function load({ fetch }) {
const res = await fetch(`/data_default.json`);
const data = await res.json();
return data;
}
}
7 changes: 5 additions & 2 deletions src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@

<svelte:head>
<title>URLinkCat</title>
<meta name="description" content="remind me change it later" />
<meta
name="description"
content="a fully customizable, multi-user, cloud-synced bookmark web app"
/>
</svelte:head>

<App data={data}/>
<App {data} />
93 changes: 37 additions & 56 deletions src/routes/App.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,17 @@
export let data;
let dataSnapshot;
let pageReadme;
let uploadingState; // TODO
let uploadingIconConfig = { color: 'green', icon: 'backup' };
const dataSizeLimit = Number(12345);
const cf_workers = 'urlinkcat.t6.workers.dev';
let needToken;
const isInstanceDemo = true;
console.log("now data is", data);
// import utils
import {DB} from '$lib/db.js';
import { DB } from '$lib/db.js';
import { newRandomID } from '$lib/utils.js';
// import markdown
// import external dependency
import * as markdown from '@logue/markdown-wasm';
import { onMount } from 'svelte';
onMount(async () => {
// await initData();
await markdown.ready();
await initData();
});
// init username
let username = window.location.hash.split('#')[1];
Expand All @@ -34,24 +23,34 @@
let db = new DB(cf_workers, username);
// Init data
async function initData(){
async function initData() {
data = await db.getData(username); //.then((result) => data = result);
data.token = ''; // fron-end-only key
data = data;
dataSnapshot = JSON.stringify(data);
data = data; // TODO: refactor in Svelte 5
dataSnapshot = JSON.stringify(data);
updatePageReadMe();
}
const updatePageReadMe = async () => {
async function updatePageReadMe() {
data = data;
pageReadme = markdown.parse(data.readme.content, {
parseFlags: markdown.ParseFlags.DEFAULT | markdown.ParseFlags.NO_HTML // NO_HTML for safety reason (xss)
});
};
}
// async init
import { onMount } from 'svelte';
onMount(async () => {
// await initData();
await markdown.ready();
await initData();
});
// init components
import Lock from './Lock.svelte';
let unlocked = false;
// page data updators
function delItem(sites, site_i) {
sites[site_i].undo = true;
data = data;
Expand Down Expand Up @@ -102,7 +101,13 @@
data = data;
}
// data processing
// page data handlers
window.onhashchange = async function () {
username = window.location.hash.split('#')[1];
db = new DB(cf_workers, username);
data = await db.getData(username);
updatePageReadMe();
};
function data_validate(currentDataStr, dataSizeLimit) {
if (currentDataStr.length > dataSizeLimit) {
Expand All @@ -116,49 +121,26 @@
alert('Nothing changed. No need to save.');
return false;
}
// else{
// console.log{currentDataStr == jsonedData, currentDataStr , jsonedData}
// }
return true;
}
const newRandomID = function () {
let result = Math.random().toString(36).slice(-8);
while (result.length < 8) {
result = Math.random().toString(36).slice(-8);
}
return result;
};
window.onhashchange = function () {
username = window.location.hash.split('#')[1];
db = new DB(cf_workers, username);
data = db.getData(username);
updatePageReadMe();
};
function tryUploadData(){
function tryUploadData() {
const currentDataStr = JSON.stringify(data);
if (!data_validate(currentDataStr, dataSizeLimit)) {
const uploadingState = 'bad';
changeIcon(uploadingState);
return false;
}
db.uploadData(currentDataStr).then(({uploadingState})=>{
changeIcon(uploadingState)
if (uploadingState=='ok'){
dataSnapshot = JSON.stringify(data);
db.uploadData(currentDataStr).then(({ uploadingState }) => {
changeIcon(uploadingState);
if (uploadingState == 'ok') {
dataSnapshot = JSON.stringify(data);
}
})
});
}
// Icon as upload indicator
function chooseIcon(uploadingState) {
switch (uploadingState) {
case 'ok':
Expand All @@ -175,16 +157,15 @@
function changeIcon(uploadingState) {
uploadingIconConfig = chooseIcon(uploadingState);
setTimeout(() => {
uploadingState = '';
changeIcon('');
uploadingState = ''; //closure
changeIcon(uploadingState);
}, 5000);
}
// Password / Token related functions
function checkToken() {
data = data;
if (['\\', '"'].some((el) => data.token.includes(el))) alert('disallowed characters');
// console.log(data.token)
}
// color-code auto correction, from "Light Blue" to "light-blue"
Expand Down Expand Up @@ -339,9 +320,9 @@

<Lock bind:unlocked />

{#if needToken}
{#if db.needToken}
<div class="auth container">
This page requires admin token to save data. Token: <input
This page requires admin authentication to save data. Auth Token: <input
id="token"
bind:value={data.token}
on:input={checkToken}
Expand Down
Loading

0 comments on commit 823120b

Please sign in to comment.