Skip to content

Commit

Permalink
[#249] added support for assigning a Promise as AsyncAuthStore initia…
Browse files Browse the repository at this point in the history
…l value
  • Loading branch information
ganigeorgiev committed Oct 7, 2023
1 parent 9f6700a commit 421e15c
Show file tree
Hide file tree
Showing 10 changed files with 76 additions and 25 deletions.
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 0.18.2

- Added support for assigning a `Promise` as `AsyncAuthStore` initial value ([#249](https://github.com/pocketbase/js-sdk/issues/249)).


## 0.18.1

- Fixed realtime subscriptions auto cancellation to use the proper `requestKey` param.
Expand Down Expand Up @@ -64,7 +69,7 @@
const store = new AsyncAuthStore({
save: async (serialized) => AsyncStorage.setItem("pb_auth", serialized),
initial: await AsyncStorage.getItem("pb_auth"),
initial: AsyncStorage.getItem("pb_auth"),
});
const pb = new PocketBase("https://example.com", store)
Expand Down
6 changes: 3 additions & 3 deletions dist/pocketbase.es.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -1205,7 +1205,7 @@ type AsyncClearFunc = () => Promise<void>;
*
* const store = new AsyncAuthStore({
* save: async (serialized) => AsyncStorage.setItem("pb_auth", serialized),
* initial: await AsyncStorage.getItem("pb_auth"),
* initial: AsyncStorage.getItem("pb_auth"),
* });
*
* const pb = new PocketBase("https://example.com", store)
Expand All @@ -1224,8 +1224,8 @@ declare class AsyncAuthStore extends BaseAuthStore {
///
/// If not explicitly set, `saveFunc` with empty data will be used.
clear?: AsyncClearFunc;
// initial data to load into the store
initial?: string;
// An *optional* initial data to load into the store.
initial?: string | Promise<any>;
});
/**
* @inheritdoc
Expand Down
6 changes: 3 additions & 3 deletions dist/pocketbase.es.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1205,7 +1205,7 @@ type AsyncClearFunc = () => Promise<void>;
*
* const store = new AsyncAuthStore({
* save: async (serialized) => AsyncStorage.setItem("pb_auth", serialized),
* initial: await AsyncStorage.getItem("pb_auth"),
* initial: AsyncStorage.getItem("pb_auth"),
* });
*
* const pb = new PocketBase("https://example.com", store)
Expand All @@ -1224,8 +1224,8 @@ declare class AsyncAuthStore extends BaseAuthStore {
///
/// If not explicitly set, `saveFunc` with empty data will be used.
clear?: AsyncClearFunc;
// initial data to load into the store
initial?: string;
// An *optional* initial data to load into the store.
initial?: string | Promise<any>;
});
/**
* @inheritdoc
Expand Down
2 changes: 1 addition & 1 deletion dist/pocketbase.es.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/pocketbase.es.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/pocketbase.es.mjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/pocketbase.es.mjs.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "0.18.1",
"version": "0.18.2",
"name": "pocketbase",
"description": "PocketBase JavaScript SDK",
"author": "Gani Georgiev",
Expand Down
28 changes: 16 additions & 12 deletions src/stores/AsyncAuthStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type queueFunc = () => Promise<void>;
*
* const store = new AsyncAuthStore({
* save: async (serialized) => AsyncStorage.setItem("pb_auth", serialized),
* initial: await AsyncStorage.getItem("pb_auth"),
* initial: AsyncStorage.getItem("pb_auth"),
* });
*
* const pb = new PocketBase("https://example.com", store)
Expand All @@ -41,15 +41,15 @@ export class AsyncAuthStore extends BaseAuthStore {
/// If not explicitly set, `saveFunc` with empty data will be used.
clear?: AsyncClearFunc,

// initial data to load into the store
initial?: string,
// An *optional* initial data to load into the store.
initial?: string|Promise<any>,
}) {
super();

this.saveFunc = config.save;
this.clearFunc = config.clear;

this._loadInitial(config.initial);
this._enqueue(() => this._loadInitial(config.initial));
}

/**
Expand Down Expand Up @@ -81,19 +81,23 @@ export class AsyncAuthStore extends BaseAuthStore {
}
}


/**
* Initializes the auth store state.
*/
private _loadInitial(payload?: string) {
if (!payload) {
return; // nothing to load
}

private async _loadInitial(payload?: string|Promise<any>) {
try {
const parsed = JSON.parse(payload) || {};
payload = payload ? await payload : null;

this.save(parsed.token || "", parsed.model || null);
if (payload) {
let parsed;
if (typeof payload === 'string') {
parsed = JSON.parse(payload) || {};
} else if (typeof payload === 'object') {
parsed = payload;
}

this.save(parsed.token || "", parsed.model || null);
}
} catch (_) {}
}

Expand Down
44 changes: 43 additions & 1 deletion tests/stores/AsyncAuthStore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ describe('AsyncAuthStore', function() {
await expect(callsPromise).resolves.toStrictEqual([]);
});

test('load initial', async function() {
test('load initial from string', async function() {
let calls: any = [];

const store = new AsyncAuthStore({
Expand All @@ -31,15 +31,57 @@ describe('AsyncAuthStore', function() {
initial: `{"token": "test", "model": {"id": "id1"}}`
});

const callsPromise = new Promise((resolve, _) => {
setTimeout(() => resolve(calls), 0);
});
await expect(callsPromise).resolves.toStrictEqual([
`{"token":"test","model":{"id":"id1"}}`,
]);

assert.equal(store.token, 'test');
assert.deepEqual(store.model, {'id': 'id1'} as any);
});

test('load initial from Promise<string>', async function() {
let calls: any = [];

const store = new AsyncAuthStore({
save: async (payload) => {
calls.push(payload);
},
initial: Promise.resolve(`{"token": "test", "model": {"id": "id1"}}`)
});

const callsPromise = new Promise((resolve, _) => {
setTimeout(() => resolve(calls), 0);
});
await expect(callsPromise).resolves.toStrictEqual([
`{"token":"test","model":{"id":"id1"}}`,
]);

assert.equal(store.token, 'test');
assert.deepEqual(store.model, {'id': 'id1'} as any);
});

test('load initial from Promise<object>', async function() {
let calls: any = [];

const store = new AsyncAuthStore({
save: async (payload) => {
calls.push(payload);
},
initial: Promise.resolve({"token": "test", "model": {"id": "id1"}})
});

const callsPromise = new Promise((resolve, _) => {
setTimeout(() => resolve(calls), 0);
});
await expect(callsPromise).resolves.toStrictEqual([
`{"token":"test","model":{"id":"id1"}}`,
]);

assert.equal(store.token, 'test');
assert.deepEqual(store.model, {'id': 'id1'} as any);
});
});

Expand Down

0 comments on commit 421e15c

Please sign in to comment.