Skip to content

Commit

Permalink
Ytta🗿
Browse files Browse the repository at this point in the history
  • Loading branch information
ImYanXiao authored Oct 8, 2024
1 parent b0c118b commit f559d4b
Showing 1 changed file with 43 additions and 37 deletions.
80 changes: 43 additions & 37 deletions lib/cloudDBAdapter.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,64 @@
import got from 'got'

const stringify = obj => JSON.stringify(obj, null, 2)
const parse = str => JSON.parse(str, (_, v) => {
if (
v !== null &&
typeof v === 'object' &&
'type' in v &&
v.type === 'Buffer' &&
'data' in v &&
Array.isArray(v.data)) {
return Buffer.from(v.data)
import got from 'got';

const stringify = (obj) => JSON.stringify(obj, null, 2);

const parse = (str) => JSON.parse(str, (_, v) => {
if (v !== null && typeof v === 'object' && 'type' in v && v.type === 'Buffer' && 'data' in v && Array.isArray(v.data)) {
return Buffer.from(v.data);
}
return v
})
return v;
});

class CloudDBAdapter {
constructor(url, {
serialize = stringify,
deserialize = parse,
fetchOptions = {}
fetchOptions = {},
} = {}) {
this.url = url
this.serialize = serialize
this.deserialize = deserialize
this.fetchOptions = fetchOptions
if (typeof url !== 'string' || !/^https?:\/\//.test(url)) {
throw new Error('Invalid URL provided.');
}

this.url = url;
this.serialize = serialize;
this.deserialize = deserialize;
this.fetchOptions = fetchOptions;
}

async read() {
try {
let res = await got(this.url, {
const res = await got(this.url, {
method: 'GET',
headers: {
'Accept': 'application/json;q=0.9,text/plain'
'Accept': 'application/json;q=0.9,text/plain',
},
...this.fetchOptions
})
if (res.statusCode !== 200) throw res.statusMessage
return this.deserialize(res.body)
...this.fetchOptions,
});

if (res.statusCode !== 200) throw new Error(res.statusMessage);
return this.deserialize(res.body);
} catch (e) {
return null
throw new Error(`Read error: ${e.message}`);
}
}

async write(obj) {
let res = await got(this.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
...this.fetchOptions,
body: this.serialize(obj)
})
if (res.statusCode !== 200) throw res.statusMessage
return res.body
try {
const res = await got(this.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
...this.fetchOptions,
body: this.serialize(obj),
});

if (res.statusCode !== 200) throw new Error(res.statusMessage);
return res.body;
} catch (e) {
throw new Error(`Write error: ${e.message}`);
}
}
}

export default CloudDBAdapter
export default CloudDBAdapter;

0 comments on commit f559d4b

Please sign in to comment.