Skip to content

Commit

Permalink
Better typing and assertions for encryptionKey
Browse files Browse the repository at this point in the history
  • Loading branch information
mugikhan committed Dec 12, 2024
1 parent e2c4436 commit 05acbae
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions packages/web/src/db/PowerSyncDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
AbstractPowerSyncDatabase,
DBAdapter,
DEFAULT_POWERSYNC_CLOSE_OPTIONS,
isDBAdapter,
isSQLOpenFactory,
PowerSyncDatabaseOptions,
PowerSyncDatabaseOptionsWithDBAdapter,
PowerSyncDatabaseOptionsWithOpenFactory,
Expand Down Expand Up @@ -82,9 +84,7 @@ export type WebPowerSyncDatabaseOptionsWithSettings = WithWebSyncOptions<
WithWebFlags<WithWebEncryptionOptions<PowerSyncDatabaseOptionsWithSettings>>
>;

export type WebPowerSyncDatabaseOptions = WithWebSyncOptions<
WithWebFlags<WithWebEncryptionOptions<PowerSyncDatabaseOptions>>
>;
export type WebPowerSyncDatabaseOptions = WithWebSyncOptions<WithWebFlags<PowerSyncDatabaseOptions>>;

export const DEFAULT_POWERSYNC_FLAGS: Required<WebPowerSyncFlags> = {
...DEFAULT_WEB_SQL_FLAGS,
Expand All @@ -99,6 +99,20 @@ export const resolveWebPowerSyncFlags = (flags?: WebPowerSyncFlags): Required<We
};
};

/**
* Asserts that the database options are valid for custom database constructors.
*/
function assertValidDatabaseOptions(options: WebPowerSyncDatabaseOptions): void {
if ('database' in options && 'encryptionKey' in options) {
const { database } = options;
if (isSQLOpenFactory(database) || isDBAdapter(database)) {
throw new Error(
`Invalid configuration: 'encryptionKey' should only be included inside the database object when using a custom ${isSQLOpenFactory(database) ? 'WASQLiteOpenFactory' : 'WASQLiteDBAdapter'} constructor.`
);
}
}
}

/**
* A PowerSync database which provides SQLite functionality
* which is automatically synced.
Expand Down Expand Up @@ -126,6 +140,8 @@ export class PowerSyncDatabase extends AbstractPowerSyncDatabase {
constructor(protected options: WebPowerSyncDatabaseOptions) {
super(options);

assertValidDatabaseOptions(options);

this.resolvedFlags = resolveWebPowerSyncFlags(options.flags);

if (this.resolvedFlags.enableMultiTabs && !this.resolvedFlags.externallyUnload) {
Expand Down

0 comments on commit 05acbae

Please sign in to comment.