From ad7c573752af344aae4ead17c54963be9d2ae56a Mon Sep 17 00:00:00 2001 From: "@wwwjim" Date: Sat, 26 Sep 2020 19:08:07 -0700 Subject: [PATCH] small refactor to getBucketAPIFromUserToken --- node_common/utilities.js | 52 +++++++++++++++++++++++++++------------- 1 file changed, 35 insertions(+), 17 deletions(-) diff --git a/node_common/utilities.js b/node_common/utilities.js index c17fef76..14e63516 100644 --- a/node_common/utilities.js +++ b/node_common/utilities.js @@ -137,6 +137,32 @@ export const getPowergateAPIFromUserToken = async ({ user }) => { }; }; +export const setupWithThread = async ({ buckets }) => { + const client = new Client(buckets.context); + + try { + const res = await client.getThread("buckets"); + + buckets.withThread(res.id.toString()); + + console.log(`[ buckets ] getThread success`); + } catch (error) { + if (error.message !== "Thread not found") { + throw new Error(error.message); + } + + const newId = ThreadID.fromRandom(); + await client.newDB(newId, "buckets"); + const threadID = newId.toString(); + + buckets.withThread(threadID); + + console.log(`[ buckets ] newDB success`); + } + + return buckets; +}; + // NOTE(jim): Requires @textile/hub export const getBucketAPIFromUserToken = async ({ user, @@ -151,28 +177,20 @@ export const getBucketAPIFromUserToken = async ({ await buckets.getToken(identity); let root = null; + console.log(`[ buckets ] getOrCreate init ${name}`); + // NOTE(jim): captures `withThread` cases. try { - const client = new Client(buckets.context); - try { - const res = await client.getThread("buckets"); + buckets = await setupWithThread({ buckets }); + } catch (e) { + console.log(`[ textile ] warning: ${e.message}`); + } - buckets.withThread(res.id.toString()); - console.log(`[ buckets ] getThread success`); - } catch (error) { - if (error.message !== "Thread not found") { - throw new Error(error.message); - } - - const newId = ThreadID.fromRandom(); - await client.newDB(newId, "buckets"); - const threadID = newId.toString(); - - buckets.withThread(threadID); - console.log(`[ buckets ] newDB success`); - } + console.log(`[ buckets ] getOrCreate thread found for ${name}`); + // NOTE(jim): captures finding your bucket and or creating a new one. + try { const roots = await buckets.list(); root = roots.find((bucket) => bucket.name === name); if (!root) {