From f559d4b7c8b9eea4c9630c128a982a890df0cefe Mon Sep 17 00:00:00 2001 From: Xiao Yan? <102222065+ImYanXiao@users.noreply.github.com> Date: Wed, 9 Oct 2024 00:31:48 +0700 Subject: [PATCH] =?UTF-8?q?Ytta=F0=9F=97=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/cloudDBAdapter.js | 80 +++++++++++++++++++++++-------------------- 1 file changed, 43 insertions(+), 37 deletions(-) diff --git a/lib/cloudDBAdapter.js b/lib/cloudDBAdapter.js index cbfbeb02e..60918dfe6 100644 --- a/lib/cloudDBAdapter.js +++ b/lib/cloudDBAdapter.js @@ -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;