Skip to content

Commit

Permalink
Merge pull request #66 from powersync-ja/improved-documentation
Browse files Browse the repository at this point in the history
Improve Readmes and code commenting
  • Loading branch information
benitav authored Feb 14, 2024
2 parents a17e14d + aee0eaf commit eec4d84
Show file tree
Hide file tree
Showing 10 changed files with 88 additions and 113 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
<a href="https://www.powersync.com" target="_blank"><img src="https://github.com/powersync-ja/.github/assets/19345049/602bafa0-41ce-4cee-a432-56848c278722"/></a>
</p>

PowerSync is a service and set of SDKs that keeps Postgres databases in sync with on-device SQLite databases.
_Bad connectivity is everywhere, and we're tired of it. PowerSync is on a mission to help developers write offline-first real-time reactive apps._

[PowerSync](https://powersync.com) is a service and set of SDKs that keeps Postgres databases in sync with on-device SQLite databases.

# PowerSync JavaScript SDKs

Expand Down Expand Up @@ -31,7 +33,7 @@ PowerSync is a service and set of SDKs that keeps Postgres databases in sync wit

## Demo Apps / Example Projects

Demo applications are located in the [`demos/`](./demos/) directory.
Demo applications are located in the [`demos/`](./demos/) directory. Also see our [Demo Apps / Example Projects](https://docs.powersync.com/resources/demo-apps-example-projects) gallery which lists all projects by the backend and client-side framework they use.

- [demos/nextjs-supabase-todolist](./demos/nextjs-supabase-todolist/): A Next.js to-do list example app using the PowerSync Web SDK and a Supabase backend.
- [demos/yjs-nextjs-supabase-text-collab](./demos/yjs-nextjs-supabase-text-collab/README.md): A Next.js real-time text editing collaboration example app powered by [Yjs](https://github.com/yjs/yjs) CRDTs and [Tiptap](https://tiptap.dev/), using the PowerSync Web SDK and a Supabase backend.
Expand Down
4 changes: 3 additions & 1 deletion packages/powersync-sdk-common/README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# PowerSync SDK common JS

This package contains pure TypeScript common functionality for the PowerSync SDK.
This package contains a TypeScript implementation of a PowerSync database connector and streaming sync bucket implementation, which is used in the following SDKs:
- [packages/powersync-sdk-react-native](./packages/powersync-sdk-react-native/README.md)
- [packages/powersync-sdk-web](./packages/powersync-sdk-web/README.md)
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,15 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
*/
protected static transactionMutex: Mutex = new Mutex();

/**
* Returns true if the connection is closed.
*/
closed: boolean;
ready: boolean;

/**
* Current connection status.
*/
currentStatus?: SyncStatus;
syncStreamImplementation?: AbstractStreamingSyncImplementation;
sdkVersion: string;
Expand Down Expand Up @@ -202,7 +208,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
}

/**
* Queues a CRUD upload when internal CRUD tables have been updated
* Queues a CRUD upload when internal CRUD tables have been updated.
*/
protected async watchCrudUploads() {
for await (const event of this.onChange({
Expand All @@ -223,7 +229,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
}

/**
* Connects to stream of events from PowerSync instance
* Connects to stream of events from the PowerSync instance.
*/
async connect(connector: PowerSyncBackendConnector) {
// close connection if one is open
Expand Down Expand Up @@ -293,7 +299,7 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
});
}

/*
/**
* Close the database, releasing resources.
*
* Also disconnects any active connection.
Expand Down Expand Up @@ -432,7 +438,8 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
}

/**
* Execute a statement and optionally return results.
* Execute a write (INSERT/UPDATE/DELETE) query
* and optionally return results.
*/
async execute(sql: string, parameters?: any[]) {
await this.waitForReady();
Expand Down Expand Up @@ -615,6 +622,9 @@ export abstract class AbstractPowerSyncDatabase extends BaseObserver<PowerSyncDB
});
}

/**
* @ignore
*/
private async executeReadOnly(sql: string, params: any[]) {
await this.waitForReady();
return this.database.readLock((tx) => tx.execute(sql, params));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { PowerSyncCredentials } from './PowerSyncCredentials';
import type { AbstractPowerSyncDatabase } from '../AbstractPowerSyncDatabase';

export interface PowerSyncBackendConnector {
/** Get credentials for PowerSync.
/** Allows the PowerSync client to retrieve an authentication token from your backend
* which is used to authenticate against the PowerSync service.
*
* This should always fetch a fresh set of credentials - don't use cached
* values.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,15 @@ import hash from 'object-hash';
*/
export type OpId = string;

/**
* Type of local change.
*/
export enum UpdateType {
/** Insert or replace existing row. All non-null columns are included in the data. Generated by INSERT statements. */
PUT = 'PUT',
/** Update existing row. Contains the id, and value of each changed column. Generated by UPDATE statements. */
PATCH = 'PATCH',
/** Delete existing row. Contains the id. Generated by DELETE statements. */
DELETE = 'DELETE'
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export enum OpTypeEnum {

export type OpTypeJSON = string;

/**
* Used internally for sync buckets.
*/
export class OpType {
static fromJSON(jsonValue: OpTypeJSON) {
return new OpType(OpTypeEnum[jsonValue]);
Expand Down
4 changes: 3 additions & 1 deletion packages/powersync-sdk-common/src/db/DBAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,14 @@ export interface DBGetUtils {
}

export interface LockContext extends DBGetUtils {
/** Execute a statement and optionally return results. */
/** Execute a single write statement. */
execute: (query: string, params?: any[] | undefined) => Promise<QueryResult>;
}

export interface Transaction extends LockContext {
/** Commit multiple changes to the local DB using the Transaction context. */
commit: () => Promise<QueryResult>;
/** Roll back multiple attempted changes using the Transaction context. */
rollback: () => Promise<QueryResult>;
}

Expand Down
3 changes: 3 additions & 0 deletions packages/powersync-sdk-common/src/utils/BaseObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ export class BaseObserver<T extends BaseListener = BaseListener> implements Base
this.listeners = {};
}

/**
* Register a listener for updates to the PowerSync client.
*/
registerListener(listener: Partial<T>): () => void {
const id = v4();
this.listeners[id] = listener;
Expand Down
34 changes: 30 additions & 4 deletions packages/powersync-sdk-react-native/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
<p align="center">
<a href="https://www.powersync.com" target="_blank"><img src="https://github.com/powersync-ja/.github/assets/19345049/602bafa0-41ce-4cee-a432-56848c278722"/></a>
</p>

# PowerSync SDK for React Native

[PowerSync](https://powersync.co) is a service and set of SDKs that keeps Postgres databases in sync with on-device SQLite databases. See a summary of features [here](https://docs.powersync.co/client-sdk-references/react-native-and-expo).
[PowerSync](https://powersync.com) is a service and set of SDKs that keeps Postgres databases in sync with on-device SQLite databases.

This package (`packages/powersync-sdk-react-native`) is the PowerSync SDK for React Native clients. It is an extension of `packages/powersync-sdk-common`.

See a summary of features [here](https://docs.powersync.co/client-sdk-references/react-native-and-expo).

# Installation

Expand Down Expand Up @@ -82,14 +90,32 @@ module.exports = function (api) {

# Native Projects

This package uses native libraries. Create native Android and iOS projects (if not created already) with
This package uses native libraries. Create native Android and iOS projects (if not created already) by running:

```bash
npx expo run:android
# OR
npx expo run:ios
```

# Learn More
# Getting Started

Our [SDK reference](https://docs.powersync.com/client-sdk-references/react-native-and-expo) contains everything you need to know to get started implementing PowerSync in your project.

# Changelog

A changelog for this SDK is available [here](https://releases.powersync.com/announcements/react-native-client-sdk).

# API Reference

The full API reference for this SDK can be found [here](https://powersync-ja.github.io/powersync-js/react-native-sdk).

# Examples

For example projects built with PowerSync and React Native, see our [Demo Apps / Example Projects](https://docs.powersync.com/resources/demo-apps-example-projects#react-native-and-expo) gallery. Most of these projects can also be found in the [`demos/`](../demos/) directory.

# Found a bug or need help?

Refer to our [full documentation](https://docs.powersync.com/client-sdk-references/react-native-and-expo) to learn more.
* Join our [Discord server](https://discord.gg/powersync) where you can browse topics from our community, ask questions, share feedback, or just say hello :)
* Please open a [GitHub issue](https://github.com/powersync-ja/powersync-js/issues) when you come across a bug.
* Have feedback or an idea? [Submit an idea](https://roadmap.powersync.com/tabs/5-roadmap/submit-idea) via our public roadmap or [schedule a chat](https://calendly.com/powersync-product/powersync-chat) with someone from our product team.
120 changes: 20 additions & 100 deletions packages/powersync-sdk-web/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
<p align="center">
<a href="https://www.powersync.com" target="_blank"><img src="https://github.com/powersync-ja/.github/assets/19345049/602bafa0-41ce-4cee-a432-56848c278722"/></a>
</p>

# PowerSync SDK for Web

[PowerSync](https://powersync.co) is a service and set of SDKs that keeps Postgres databases in sync with on-device SQLite databases.
[PowerSync](https://powersync.com) is a service and set of SDKs that keeps Postgres databases in sync with on-device SQLite databases.

This package (`packages/powersync-sdk-web`) is the PowerSync SDK for JavaScript Web clients. It is an extension of `packages/powersync-sdk-common`.

See a summary of features [here](https://docs.powersync.com/client-sdk-references/js-web).

## Beta Release

Expand All @@ -24,114 +32,26 @@ Install it in your app with:
npm install @journeyapps/wa-sqlite
```

## Logging

This package uses [js-logger](https://www.npmjs.com/package/js-logger) for logging.

Enable JS Logger with your logging interface of choice or use the default `console`

```JavaScript
import Logger from 'js-logger';

// Log messages will be written to the window's console.
Logger.useDefaults();
```

Enable verbose output in the developer tools for detailed logs.

The WASQLite DB Adapter opens SQLite connections inside a shared webworker. This worker can be inspected in Chrome by accessing

```
chrome://inspect/#workers
```

# Getting Started

See our [Docs](https://docs.powersync.co/usage/installation/client-side-setup) for detailed instructions.

```JavaScript
import {
Column,
ColumnType,
WASQLitePowerSyncDatabaseOpenFactory,
Schema,
Table
} from '@journeyapps/powersync-sdk-web';

export const AppSchema = new Schema([
new Table({ name: 'customers', columns: [new Column({ name: 'name', type: ColumnType.TEXT })] })
]);

let PowerSync;

export const openDatabase = async () => {
PowerSync = new WASQLitePowerSyncDatabaseOpenFactory({
schema: AppSchema,
dbFilename: 'test.sqlite',
flags: {
// This is disabled once CSR+SSR functionality is verified to be working correctly
disableSSRWarning: true,
}}).getInstance();

await PowerSync.init();

// Run local statements.
await PowerSync.execute('INSERT INTO customers(id, name) VALUES(uuid(), ?)', ['Fred']);
};

class Connector {
async fetchCredentials() {
// TODO logic to fetch a session
return {
endpoint: '[The PowerSync instance URL]',
token: 'An authentication token',
expiresAt: 'When the token expires',
};
}

async uploadData(database) {
// Upload local changes to backend, see docs for example
}
}

export const connectPowerSync = async () => {
const connector = new Connector(); // Which was declared above
await PowerSync.connect(connector);
};
Our [full SDK reference](https://docs.powersync.com/client-sdk-references/js-web) contains everything you need to know to get started implementing PowerSync in your project.

```

React hooks are available in the [@journeyapps/powersync-react](https://www.npmjs.com/package/@journeyapps/powersync-react) package
# Changelog

## Multiple Tab Support
A changelog for this SDK is available [here](https://releases.powersync.com/announcements/powersync-js-web-client-sdk).

Using PowerSync between multiple tabs is supported on some web browsers. Multiple tab support relies on shared web workers for DB and sync streaming operations. When enabled shared web workers named `shared-sync-[dbFileName]` and `shared-DB-worker-[dbFileName]` will be created.
# API Reference

The shared database worker will ensure writes to the DB will instantly be available between tabs.
The full API reference for this SDK can be found [here](https://powersync-ja.github.io/powersync-js/web-sdk).

The shared sync worker will co-ordinate for one active tab to connect to the PowerSync instance and share the latest sync state between tabs.
# Examples

Currently using the SDK in multiple tabs without enabling the `enableMultiTabs` flag will spawn a standard web worker per tab for DB operations. These workers are safe to operate on the DB concurrently, however changes from one tab may not update watches on other tabs. Only one tab can sync from the PowerSync instance at a time. The sync status will not be shared between tabs, only the oldest tab will connect and display the latest sync status.
For example projects built with PowerSync on Web, see our [Demo Apps / Example Projects](https://docs.powersync.com/resources/demo-apps-example-projects#js-web) gallery. Most of these projects can also be found in the [`demos/`](../demos/) directory.

Multiple tab support is not currently available on Android or Safari.
# Found a bug or need help?

Support is enabled by default if available. This can be disabled as below:

```Javascript
PowerSync = new WASQLitePowerSyncDatabaseOpenFactory({
schema: AppSchema,
dbFilename: 'test.sqlite',
flags: {
// This is disabled once CSR+SSR functionality is verified to be working correctly
disableSSRWarning: true,
/**
* Multiple tab support is enabled by default if available. This can be disabled by
* setting this flag to false.
*/
enableMultiTabs: false
}}).getInstance();
```
* Join our [Discord server](https://discord.gg/powersync) where you can browse topics from our community, ask questions, share feedback, or just say hello :)
* Please open a [GitHub issue](https://github.com/powersync-ja/powersync-js/issues) when you come across a bug.
* Have feedback or an idea? [Submit an idea](https://roadmap.powersync.com/tabs/5-roadmap/submit-idea) via our public roadmap or [schedule a chat](https://calendly.com/powersync-product/powersync-chat) with someone from our product team.

## Demo Apps

See the [list of demo apps](https://github.com/powersync-ja/powersync-web-sdk/?tab=readme-ov-file#demos) in the repo README.

0 comments on commit eec4d84

Please sign in to comment.