-
Notifications
You must be signed in to change notification settings - Fork 58
Add NodeJS implementation #516
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
42 commits
Select commit
Hold shift + click to select a range
ef1740c
Add Node.js support
spinda 3143158
Merge branch 'node' of github.com:spinda/powersync-js into node
simolus3 5923f6f
Override better-sqlite3 globally
simolus3 7c0c6c7
Load core extension in node demo
simolus3 afd62ab
Reformat example
simolus3 b287b4f
Test watching queries and uploads
simolus3 1064c65
Add tests to node package
simolus3 ed94f24
Add vitest workspace configuration
simolus3 3e1d9fd
Merge branch 'chore/vitest-workspace' into node
simolus3 1b334f9
Complete simple nodejs tests
simolus3 aedf8a9
Split implementation into more files
simolus3 7873694
Reduce API surface
simolus3 6cbc405
Ignore exceptions during rollback
simolus3 6c4b958
Remove better-sqlite dependency from demo
simolus3 073b28a
Node: Add readme
simolus3 30bec88
Update lockfile
simolus3 1e6b1d1
Remove toComlink with cast
simolus3 3f679b6
FIx worker URL
simolus3 23490e6
Rename demo script to start
simolus3 12c6649
Add changeset for node package
simolus3 a6e697b
Update readme in demo project
simolus3 d5a856a
Update other readmes
simolus3 02412a4
readme typo
simolus3 648202e
Disable tests for node package temporarily
simolus3 de0d0de
Use forked better-sqlite3
simolus3 1b1e805
Fix verdaccio config for better-sqlite3
simolus3 3b411f9
Merge remote-tracking branch 'origin/main' into node
simolus3 09768bb
Remove unused better-sqlite3 types
simolus3 447fcb8
Make things a bit clearer in the demo app Readme
benitav a03945a
More logs
simolus3 2dbda54
Apply throttle to node watch test
simolus3 d95a394
Skip watch test
simolus3 a5a5650
Merge remote-tracking branch 'origin/main' into node
simolus3 b941ac8
Use zero version for future changeset bump
simolus3 8de293f
Support uploads in node demo
simolus3 b247cb2
Use uuid for generated owner
simolus3 e5a57a5
Include node in docs build
simolus3 2b0f13a
NodeJS -> Node.js
benitav 2d0e1ef
casing
benitav 895983b
Also rename to Node.js in top-level readme
simolus3 3e3a287
Add thanks section to node readme
simolus3 87179ff
Merge remote-tracking branch 'origin/main' into node
simolus3 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'@powersync/node': minor | ||
--- | ||
|
||
Initial version |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
BACKEND=http://localhost:6060 | ||
SYNC_SERVICE=http://localhost:8080 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
## Node.js Demo | ||
|
||
This demonstrates a small Node.js client opening a database and connecting PowerSync. | ||
|
||
This demo is configured to talk to an example backend [you can host yourself](https://github.com/powersync-ja/self-host-demo). To get started: | ||
|
||
1. Start one of the Node.js backend examples from [the self-host-demo repository](https://github.com/powersync-ja/self-host-demo). | ||
2. If necessary, change `.env` to point to the started backend and sync service. | ||
3. Run `pnpm install` and `pnpm build:packages` in the root of this repo. | ||
4. In this directory, run `pnpm run start`. | ||
|
||
This opens the local database, connects to PowerSync, waits for a first sync and then runs a simple query. | ||
Results from the query are printed every time it changes. Try: | ||
|
||
1. Updating a row in the backend database and see changes reflected in the running client. | ||
2. Enter `add('my list')` and see the new list show up in the backend database. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
{ | ||
"name": "example-node", | ||
"version": "1.0.0", | ||
"description": "", | ||
"type": "module", | ||
"private": true, | ||
"scripts": { | ||
"build": "tsc -b", | ||
"watch": "tsc -b -w", | ||
"start": "node --loader ts-node/esm -r dotenv/config src/main.ts" | ||
}, | ||
"dependencies": { | ||
"@powersync/node": "workspace:*", | ||
"dotenv": "^16.4.7" | ||
}, | ||
"devDependencies": { | ||
"ts-node": "^10.9.2", | ||
"typescript": "^5.8.2" | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
import repl_factory from 'node:repl'; | ||
import { once } from 'node:events'; | ||
|
||
import { PowerSyncDatabase, SyncStreamConnectionMethod } from '@powersync/node'; | ||
import Logger from 'js-logger'; | ||
import { AppSchema, DemoConnector } from './powersync.js'; | ||
import { exit } from 'node:process'; | ||
|
||
const main = async () => { | ||
Logger.useDefaults({ defaultLevel: Logger.WARN }); | ||
|
||
if (!('BACKEND' in process.env) || !('SYNC_SERVICE' in process.env)) { | ||
console.warn( | ||
'Set the BACKEND and SYNC_SERVICE environment variables to point to a sync service and a running demo backend.' | ||
); | ||
return; | ||
} | ||
|
||
const db = new PowerSyncDatabase({ | ||
schema: AppSchema, | ||
database: { | ||
dbFilename: 'test.db' | ||
}, | ||
logger: Logger | ||
}); | ||
console.log(await db.get('SELECT powersync_rs_version();')); | ||
|
||
await db.connect(new DemoConnector(), { connectionMethod: SyncStreamConnectionMethod.HTTP }); | ||
await db.waitForFirstSync(); | ||
console.log('First sync complete!'); | ||
|
||
let hasFirstRow: ((value: any) => void) | null = null; | ||
const firstRow = new Promise((resolve) => (hasFirstRow = resolve)); | ||
const watchLists = async () => { | ||
for await (const rows of db.watch('SELECT * FROM lists')) { | ||
if (hasFirstRow) { | ||
hasFirstRow(null); | ||
hasFirstRow = null; | ||
} | ||
console.log('Has todo lists', rows.rows?._array); | ||
} | ||
}; | ||
|
||
watchLists(); | ||
await firstRow; | ||
|
||
console.log('Connected to PowerSync. Try updating the lists in the database and see it reflected here.'); | ||
console.log("To upload a list here, enter `await add('name of new list');`"); | ||
|
||
const repl = repl_factory.start(); | ||
repl.context.add = async (name: string) => { | ||
await db.execute( | ||
"INSERT INTO lists (id, created_at, name, owner_id) VALUEs (uuid(), datetime('now'), ?, uuid());", | ||
[name] | ||
); | ||
}; | ||
|
||
await once(repl, 'exit'); | ||
console.log('shutting down'); | ||
await db.disconnect(); | ||
await db.close(); | ||
exit(0); | ||
}; | ||
|
||
await main(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
import { AbstractPowerSyncDatabase, column, PowerSyncBackendConnector, Schema, Table } from '@powersync/node'; | ||
|
||
export class DemoConnector implements PowerSyncBackendConnector { | ||
async fetchCredentials() { | ||
const response = await fetch(`${process.env.BACKEND}/api/auth/token`); | ||
if (response.status != 200) { | ||
throw 'Could not fetch token'; | ||
} | ||
|
||
const { token } = await response.json(); | ||
|
||
return { | ||
endpoint: process.env.SYNC_SERVICE!, | ||
token: token | ||
}; | ||
} | ||
|
||
async uploadData(database: AbstractPowerSyncDatabase) { | ||
const batch = await database.getCrudBatch(); | ||
if (batch == null) { | ||
return; | ||
} | ||
|
||
const entries: any[] = []; | ||
for (const op of batch.crud) { | ||
entries.push({ | ||
table: op.table, | ||
op: op.op, | ||
id: op.id, | ||
data: op.opData | ||
}); | ||
} | ||
|
||
const response = await fetch(`${process.env.BACKEND}/api/data/`, { | ||
method: 'POST', | ||
headers: {'Content-Type': 'application/json'}, | ||
body: JSON.stringify({batch: entries}), | ||
}); | ||
if (response.status !== 200) { | ||
throw new Error(`Server returned HTTP ${response.status}: ${await response.text()}`); | ||
} | ||
|
||
await batch?.complete(); | ||
} | ||
} | ||
|
||
export const LIST_TABLE = 'lists'; | ||
export const TODO_TABLE = 'todos'; | ||
|
||
const todos = new Table( | ||
{ | ||
list_id: column.text, | ||
created_at: column.text, | ||
completed_at: column.text, | ||
description: column.text, | ||
created_by: column.text, | ||
completed_by: column.text, | ||
completed: column.integer, | ||
photo_id: column.text | ||
}, | ||
{ indexes: { list: ['list_id'] } } | ||
); | ||
|
||
const lists = new Table({ | ||
created_at: column.text, | ||
name: column.text, | ||
owner_id: column.text | ||
}); | ||
|
||
export const AppSchema = new Schema({ | ||
lists, | ||
todos | ||
}); | ||
|
||
export type Database = (typeof AppSchema)['types']; | ||
export type TodoRecord = Database['todos']; | ||
export type ListRecord = Database['lists']; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
{ | ||
"extends": "../../tsconfig.base", | ||
"compilerOptions": { | ||
"baseUrl": ".", | ||
"rootDir": "src", | ||
"outDir": "lib", | ||
"strictNullChecks": true | ||
}, | ||
"references": [ | ||
{ | ||
"path": "../../packages/node" | ||
} | ||
] | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
# @powersync/node |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.