From a562edbac611bd085f78b1c6c5c4c834d405723b Mon Sep 17 00:00:00 2001 From: wylfent Date: Sat, 26 Sep 2020 19:31:11 +0700 Subject: [PATCH] feat(@aws-amplify/datastore): support indexeddb adapter on web worker (#6874) --- packages/core/src/JS.ts | 10 ++++++++++ .../src/storage/adapter/getDefaultAdapter/index.ts | 4 ++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/core/src/JS.ts b/packages/core/src/JS.ts index 9a0004b4f9f..70dbd902041 100644 --- a/packages/core/src/JS.ts +++ b/packages/core/src/JS.ts @@ -162,6 +162,15 @@ export const makeQuerablePromise = promise => { return result; }; +export const isWebWorker = () => { + if (typeof self === 'undefined') { + return false; + } + const selfContext = self as { WorkerGlobalScope? }; + return typeof selfContext.WorkerGlobalScope !== 'undefined' && + self instanceof selfContext.WorkerGlobalScope; +}; + export const browserOrNode = () => { const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined'; @@ -268,6 +277,7 @@ export class JS { static isTextFile = isTextFile; static generateRandomString = generateRandomString; static makeQuerablePromise = makeQuerablePromise; + static isWebWorker = isWebWorker; static browserOrNode = browserOrNode; static transferKeyToLowerCase = transferKeyToLowerCase; static transferKeyToUpperCase = transferKeyToUpperCase; diff --git a/packages/datastore/src/storage/adapter/getDefaultAdapter/index.ts b/packages/datastore/src/storage/adapter/getDefaultAdapter/index.ts index e8d0af0bfc5..421860e4231 100644 --- a/packages/datastore/src/storage/adapter/getDefaultAdapter/index.ts +++ b/packages/datastore/src/storage/adapter/getDefaultAdapter/index.ts @@ -1,10 +1,10 @@ -import { browserOrNode } from '@aws-amplify/core'; +import { browserOrNode, isWebWorker } from '@aws-amplify/core'; import { Adapter } from '..'; const getDefaultAdapter: () => Adapter = () => { const { isBrowser } = browserOrNode(); - if (isBrowser && window.indexedDB) { + if ((isBrowser && window.indexedDB) || (isWebWorker() && self.indexedDB)) { return require('../indexeddb').default; }