Skip to content

Commit

Permalink
[docs] Changed code examples and bumped dev dependency (#35)
Browse files Browse the repository at this point in the history
* changed code examples

* changing examples to use at with a date. Bumped dependency for audit

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update examples/workers.js

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update examples/workers.js

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

* Update README.md

consistent quotes

Co-authored-by: Andrei Pechkurov <[email protected]>

---------

Co-authored-by: Andrei Pechkurov <[email protected]>
  • Loading branch information
javier and puzpuzpuz authored Jul 25, 2024
1 parent d4fc1bf commit 92fd173
Show file tree
Hide file tree
Showing 7 changed files with 218 additions and 218 deletions.
135 changes: 70 additions & 65 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,77 +22,80 @@ For more details, please, check the <a href="Sender.html">Sender</a>'s documenta
### Basic API usage

```javascript
const { Sender } = require('@questdb/nodejs-client');
const { Sender } = require("@questdb/nodejs-client")

async function run() {
// create a sender using HTTP protocol
const sender = Sender.fromConfig('http::addr=localhost:9000');

// add rows to the buffer of the sender
await sender.table('prices').symbol('instrument', 'EURUSD')
.floatColumn('bid', 1.0195).floatColumn('ask', 1.0221)
.at(Date.now(), 'ms');
await sender.table('prices').symbol('instrument', 'GBPUSD')
.floatColumn('bid', 1.2076).floatColumn('ask', 1.2082)
.at(Date.now(), 'ms');

// flush the buffer of the sender, sending the data to QuestDB
// the buffer is cleared after the data is sent, and the sender is ready to accept new data
await sender.flush();

// add rows to the buffer again, and send it to the server
await sender.table('prices').symbol('instrument', 'EURUSD')
.floatColumn('bid', 1.0197).floatColumn('ask', 1.0224)
.at(Date.now(), 'ms');
await sender.flush();

// close the connection after all rows ingested
await sender.close();
// create a sender using HTTP protocol
const sender = Sender.fromConfig("http::addr=127.0.0.1:9000")

// add rows to the buffer of the sender
await sender
.table("trades")
.symbol("symbol", "ETH-USD")
.symbol("side", "sell")
.floatColumn("price", 2615.54)
.floatColumn("amount", 0.00044)
.at(Date.now(), "ms")

// flush the buffer of the sender, sending the data to QuestDB
// the buffer is cleared after the data is sent, and the sender is ready to accept new data
await sender.flush()

// close the connection after all rows ingested
// unflushed data will be lost
await sender.close()
}

run()
.then(console.log)
.catch(console.error);
run().then(console.log).catch(console.error)
```

### Authentication and secure connection

```javascript
const { Sender } = require('@questdb/nodejs-client');
const { Sender } = require("@questdb/nodejs-client")

async function run() {
// create a sender using HTTPS protocol with username and password authentication
const sender = Sender.fromConfig('https::addr=localhost:9000;username=user1;password=pwd');
const sender = Sender.fromConfig("https::addr=127.0.0.1:9000;username=admin;password=quest;")

// send the data over the authenticated and secure connection
await sender.table('prices').symbol('instrument', 'EURUSD')
.floatColumn('bid', 1.0197).floatColumn('ask', 1.0224)
.at(Date.now(), 'ms');
await sender.flush();
await sender
.table("trades")
.symbol("symbol", "ETH-USD")
.symbol("side", "sell")
.floatColumn("price", 2615.54)
.floatColumn("amount", 0.00044)
.at(Date.now(), "ms")
await sender.flush()

// close the connection after all rows ingested
await sender.close();
await sender.close()
}

run().catch(console.error);
run().catch(console.error)
```

### TypeScript example

```typescript
import { Sender } from '@questdb/nodejs-client';
import { Sender } from "@questdb/nodejs-client"

async function run(): Promise<number> {
async function run(): Promise<void> {
// create a sender using HTTPS protocol with bearer token authentication
const sender: Sender = Sender.fromConfig('https::addr=localhost:9000;token=Xyvd3er6GF87ysaHk');
const sender: Sender = Sender.fromConfig("https::addr=127.0.0.1:9000;token=Xyvd3er6GF87ysaHk;")

// send the data over the authenticated and secure connection
sender.table('prices').symbol('instrument', 'EURUSD')
.floatColumn('bid', 1.0197).floatColumn('ask', 1.0224).at(Date.now(), 'ms');
await sender.flush();
await sender
.table("trades")
.symbol("symbol", "ETH-USD")
.symbol("side", "sell")
.floatColumn("price", 2615.54)
.floatColumn("amount", 0.00044)
.at(Date.now(), "ms")
await sender.flush()

// close the connection after all rows ingested
await sender.close();
await sender.close()
}

run().catch(console.error);
Expand All @@ -101,77 +104,79 @@ run().catch(console.error);
### Worker threads example

```javascript
const { Sender } = require('@questdb/nodejs-client');
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const { Sender } = require("@questdb/nodejs-client")
const { Worker, isMainThread, parentPort, workerData } = require("worker_threads")

// fake venue
// generates random prices for a ticker for max 5 seconds, then the feed closes
// generates random prices and amounts for a ticker for max 5 seconds, then the feed closes
function* venue(ticker) {
let end = false;
setTimeout(() => { end = true; }, rndInt(5000));
let end = false
setTimeout(() => { end = true; }, rndInt(5000))
while (!end) {
yield {'ticker': ticker, 'price': Math.random()};
yield {ticker, price: Math.random(), amount: Math.random()}
}
}

// market data feed simulator
// uses the fake venue to deliver price updates to the feed handler (onTick() callback)
// uses the fake venue to deliver price and amount updates to the feed handler (onTick() callback)
async function subscribe(ticker, onTick) {
const feed = venue(workerData.ticker);
const feed = venue(workerData.ticker)
let tick;
while (tick = feed.next().value) {
await onTick(tick);
await sleep(rndInt(30));
await onTick(tick)
await sleep(rndInt(30))
}
}

async function run() {
if (isMainThread) {
const tickers = ['t1', 't2', 't3', 't4'];
const tickers = ["ETH-USD", "BTC-USD", "SOL-USD", "DOGE-USD"]
// main thread to start a worker thread for each ticker
for (let ticker in tickers) {
for (let ticker of tickers) {
const worker = new Worker(__filename, { workerData: { ticker: ticker } })
.on('error', (err) => { throw err; })
.on('exit', () => { console.log(`${ticker} thread exiting...`); })
.on('message', (msg) => {
console.log(`Ingested ${msg.count} prices for ticker ${msg.ticker}`);
console.log(`Ingested ${msg.count} prices for ticker ${msg.ticker}`)
});
}
} else {
// it is important that each worker has a dedicated sender object
// threads cannot share the sender because they would write into the same buffer
const sender = Sender.fromConfig('http::addr=localhost:9000');
const sender = Sender.fromConfig("http::addr=127.0.0.1:9000");

// subscribe for the market data of the ticker assigned to the worker
// ingest each price update into the database using the sender
let count = 0;
await subscribe(workerData.ticker, async (tick) => {
await sender
.table('prices')
.symbol('ticker', tick.ticker)
.floatColumn('price', tick.price)
.at(Date.now(), 'ms');
.table("trades")
.symbol("symbol", tick.ticker)
.symbol("side", "sell")
.floatColumn("price", tick.price)
.floatColumn("amount", tick.amount)
.at(Date.now(), "ms")
await sender.flush();
count++;
});

// let the main thread know how many prices were ingested
parentPort.postMessage({'ticker': workerData.ticker, 'count': count});
parentPort.postMessage({ticker: workerData.ticker, count})

// close the connection to the database
await sender.close();
await sender.close()
}
}

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
return new Promise(resolve => setTimeout(resolve, ms))
}

function rndInt(limit) {
return Math.floor((Math.random() * limit) + 1);
return Math.floor((Math.random() * limit) + 1)
}

run()
.then(console.log)
.catch(console.error);
.catch(console.error)
```
44 changes: 22 additions & 22 deletions examples/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,40 @@ const { Sender } = require('@questdb/nodejs-client');

async function run() {
// authentication details
const CLIENT_ID = 'testapp';
const PRIVATE_KEY = '9b9x5WhJywDEuo1KGQWSPNxtX-6X6R2BRCKhYMMY6n8';
const CLIENT_ID = 'admin'
const PRIVATE_KEY = 'ZRxmCOQBpZoj2fZ-lEtqzVDkCre_ouF3ePpaQNDwoQk'
const AUTH = {
keyId: CLIENT_ID,
token: PRIVATE_KEY
};
}

// pass the authentication details to the sender
const sender = new Sender({ protocol: 'tcp', host: 'localhost', port: 9009, bufferSize: 4096, auth: AUTH });
await sender.connect();
const sender = new Sender({ protocol: 'tcp', host: '127.0.0.1', port: 9009, bufferSize: 4096, auth: AUTH })
await sender.connect()

// send the data over the authenticated connection
let bday = Date.parse('1856-07-10');
await sender
.table('inventors_nodejs')
.symbol('born', 'Austrian Empire')
.timestampColumn('birthday', bday, 'ms') // epoch in millis
.intColumn('id', 0)
.stringColumn('name', 'Nicola Tesla')
.at(Date.now(), 'ms'); // epoch in millis
bday = Date.parse('1847-02-11');
.table("trades")
.symbol("symbol", "ETH-USD")
.symbol("side", "sell")
.floatColumn("price", 2615.54)
.floatColumn("amount", 0.00044)
.at(Date.now(), 'ms')

// add rows to the buffer of the sender
await sender
.table('inventors_nodejs')
.symbol('born', 'USA')
.timestampColumn('birthday', bday, 'ms')
.intColumn('id', 1)
.stringColumn('name', 'Thomas Alva Edison')
.at(Date.now(), 'ms');
.table("trades")
.symbol("symbol", "BTC-USD")
.symbol("side", "sell")
.floatColumn("price", 39269.98)
.floatColumn("amount", 0.001)
.at(Date.now(), 'ms')

// flush the buffer of the sender, sending the data to QuestDB
await sender.flush();
await sender.flush()

// close the connection after all rows ingested
await sender.close();
await sender.close()
}

run().catch(console.error);
run().catch(console.error)
46 changes: 23 additions & 23 deletions examples/auth_tls.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,40 +2,40 @@ const { Sender } = require('@questdb/nodejs-client');

async function run() {
// authentication details
const CLIENT_ID = 'testapp';
const PRIVATE_KEY = '9b9x5WhJywDEuo1KGQWSPNxtX-6X6R2BRCKhYMMY6n8';
const CLIENT_ID = 'admin'
const PRIVATE_KEY = 'ZRxmCOQBpZoj2fZ-lEtqzVDkCre_ouF3ePpaQNDwoQk'
const AUTH = {
keyId: CLIENT_ID,
token: PRIVATE_KEY
};
}

// pass the authentication details to the sender
const sender = new Sender({ protocol: 'tcps', host: 'localhost', port: 9009, bufferSize: 4096, auth: AUTH });
await sender.connect();
const sender = new Sender({ protocol: 'tcps', host: '127.0.0.1', port: 9009, bufferSize: 4096, auth: AUTH })
await sender.connect()

// send the data over the authenticated and secure connection
let bday = Date.parse('1856-07-10');
// send the data over the authenticated connection
await sender
.table('inventors_nodejs')
.symbol('born', 'Austrian Empire')
.timestampColumn('birthday', bday, 'ms') // epoch in millis
.intColumn('id', 0)
.stringColumn('name', 'Nicola Tesla')
.at(Date.now(), 'ms'); // epoch in millis
bday = Date.parse('1847-02-11');
.table("trades")
.symbol("symbol", "ETH-USD")
.symbol("side", "sell")
.floatColumn("price", 2615.54)
.floatColumn("amount", 0.00044)
.at(Date.now(), 'ms')

// add rows to the buffer of the sender
await sender
.table('inventors_nodejs')
.symbol('born', 'USA')
.timestampColumn('birthday', bday, 'ms')
.intColumn('id', 1)
.stringColumn('name', 'Thomas Alva Edison')
.at(Date.now(), 'ms');
.table("trades")
.symbol("symbol", "BTC-USD")
.symbol("side", "sell")
.floatColumn("price", 39269.98)
.floatColumn("amount", 0.001)
.at(Date.now(), 'ms')

// flush the buffer of the sender, sending the data to QuestDB
await sender.flush();
await sender.flush()

// close the connection after all rows ingested
await sender.close();
await sender.close()
}

run().catch(console.error);
run().catch(console.error)
Loading

0 comments on commit 92fd173

Please sign in to comment.