mirror of
https://github.com/DeBrosOfficial/network-ts-sdk.git
synced 2025-12-10 09:38:50 +00:00
3.9 KiB
3.9 KiB
Quick Start Guide for @network/sdk
5-Minute Setup
1. Install
npm install @network/sdk
2. Create a Client
import { createClient } from "@network/sdk";
const client = createClient({
baseURL: "http://localhost:6001",
apiKey: "ak_your_api_key:default", // Get from gateway
});
3. Use It
Database:
await client.db.createTable("CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT)");
await client.db.exec("INSERT INTO posts (title) VALUES (?)", ["Hello"]);
const posts = await client.db.query("SELECT * FROM posts");
Pub/Sub:
const sub = await client.pubsub.subscribe("news", {
onMessage: (msg) => console.log(msg.data),
});
await client.pubsub.publish("news", "Update!");
sub.close();
Network:
const healthy = await client.network.health();
const status = await client.network.status();
Running Tests Locally
Prerequisites
- Bootstrap node must be running (provides database on port 5001)
- Gateway must be running (provides REST API on port 6001)
# Terminal 1: Start bootstrap node
cd ../network
make run-node
# Terminal 2: Start gateway (after bootstrap is ready)
cd ../network
make run-gateway
# Terminal 3: Run E2E tests
cd ../network-ts-sdk
export GATEWAY_BASE_URL=http://localhost:6001
export GATEWAY_API_KEY=ak_RsJJXoENynk_5jTJEeM4wJKx:default
pnpm run test:e2e
Note: The gateway configuration now correctly uses port 5001 for RQLite (not 4001 which is P2P).
Building for Production
npm run build
# Output in dist/
Key Classes
| Class | Purpose |
|---|---|
createClient() |
Factory function, returns Client |
AuthClient |
Authentication, token management |
DBClient |
Database operations (exec, query, etc.) |
QueryBuilder |
Fluent SELECT builder |
Repository<T> |
Generic entity pattern |
PubSubClient |
Pub/sub operations |
NetworkClient |
Network status, peers |
SDKError |
All errors inherit from this |
Common Patterns
QueryBuilder
const items = await client.db
.createQueryBuilder("items")
.where("status = ?", ["active"])
.andWhere("price > ?", [10])
.orderBy("created_at DESC")
.limit(20)
.getMany();
Repository
interface User { id?: number; email: string; }
const repo = client.db.repository<User>("users");
// Save (insert or update)
const user: User = { email: "alice@example.com" };
await repo.save(user);
// Find
const found = await repo.findOne({ email: "alice@example.com" });
Transaction
await client.db.transaction([
{ kind: "exec", sql: "INSERT INTO logs (msg) VALUES (?)", args: ["Event A"] },
{ kind: "query", sql: "SELECT COUNT(*) FROM logs", args: [] },
]);
Error Handling
import { SDKError } from "@network/sdk";
try {
await client.db.query("SELECT * FROM invalid_table");
} catch (error) {
if (error instanceof SDKError) {
console.error(`${error.httpStatus}: ${error.message}`);
}
}
TypeScript Types
Full type safety - use autocomplete in your IDE:
const status: NetworkStatus = await client.network.status();
const users: User[] = await repo.find({ active: 1 });
const msg: Message = await subscription.onMessage((m) => m);
Next Steps
- Read the full README.md
- Explore tests/e2e/ for examples
- Check IMPLEMENTATION_SUMMARY.md for architecture
Troubleshooting
"Failed to connect to gateway"
- Check
GATEWAY_BASE_URLis correct - Ensure gateway is running
- Verify network connectivity
"API key invalid"
- Confirm
apiKeyformat:ak_key:namespace - Get a fresh API key from gateway admin
"WebSocket connection failed"
- Gateway must support WebSocket at
/v1/pubsub/ws - Check firewall settings
"Tests skip"
- Set
GATEWAY_API_KEYenvironment variable - Tests gracefully skip without it