sqlcrud-client
v1.0.0
Published
HTTP client library for sqlcrud SQLite REST API
Maintainers
Readme
sqlcrud-client
HTTP client library for the sqlcrud SQLite REST API. Works in browsers and Node.js (native fetch, zero runtime dependencies).
Installation
npm install sqlcrud-clientQuick Start
import { SqlCrudClient } from 'sqlcrud-client';
const client = new SqlCrudClient({
baseUrl: 'http://localhost:3123',
username: 'admin',
password: 'password',
});
// List tables
const tables = await client.listTables();
// Create a schema
await client.setSchema('users', {
name: { type: 'string', length: 100, primary: true },
email: { type: 'string', unique: true },
active: { type: 'boolean' },
});
// Create a record (booleans coerced to 1/0 automatically)
const user = await client.createRecord('users', {
name: 'Alice',
email: '[email protected]',
active: true,
});
// Query records
const activeUsers = await client.queryRecords('users', { active: 1 });
// Update a record
const result = await client.updateRecord('users', { name: 'Alice' }, { email: '[email protected]' });
console.log(result.before, result.after);
// Delete records
await client.deleteRecord('users', { name: 'Alice' });Constructor
new SqlCrudClient(config)| Option | Type | Required | Description |
|--------|------|----------|-------------|
| baseUrl | string | Yes | sqlcrud server URL (e.g. 'http://localhost:3123') |
| username | string | No | Username for Basic Auth |
| password | string | No | Password for Basic Auth |
| headers | object | No | Additional headers sent with every request |
API Methods
Schema Management
| Method | HTTP | Description |
|--------|------|-------------|
| listTables() | GET /api/tables | Returns string[] of table names |
| listModels() | GET /api/models | Returns model info array |
| getSchema(model) | GET /api/schema/:model | Returns schema definition object |
| setSchema(model, schema) | POST /api/schema/:model | Create or update a schema |
| deleteSchema(model) | DELETE /api/schema/:model | Delete schema and drop table |
Record Operations
| Method | HTTP | Description |
|--------|------|-------------|
| queryRecords(model, params?) | GET /api/record/:model | Query records by field criteria (returns [] if no match) |
| createRecord(model, data) | POST /api/record/:model | Create a new record |
| updateRecord(model, criteria, data) | PUT /api/record/:model | Update a record (criteria must match exactly one row) |
| deleteRecord(model, criteria) | DELETE /api/record/:model | Delete records matching criteria |
Error Handling
All errors extend SqlCrudError for easy instanceof checking:
import { SqlCrudError, SqlCrudAuthError, SqlCrudNotFoundError } from 'sqlcrud-client';
try {
await client.getSchema('nonexistent');
} catch (err) {
if (err instanceof SqlCrudAuthError) {
console.error('Authentication failed');
} else if (err instanceof SqlCrudNotFoundError) {
console.error('Model not found');
} else if (err instanceof SqlCrudError) {
console.error('Error:', err.message, 'Status:', err.statusCode);
}
}| Error Class | When |
|-------------|------|
| SqlCrudError | Base class for all library errors |
| SqlCrudAuthError | 401 Unauthorized |
| SqlCrudNotFoundError | 404 Not Found |
| SqlCrudValidationError | Client-side validation failure |
| SqlCrudServerError | 5xx server error |
All errors expose statusCode (number) and endpoint (string).
Utility Functions
Import standalone (tree-shakeable):
import { validateSchema, coerceBooleans, FIELD_TYPES } from 'sqlcrud-client/utils';Validation
validateIdentifier(name, label?)— Validates model/field names against^[a-zA-Z_][a-zA-Z0-9_]*$validateFieldName(name)— Validates field names (identifier + reserved name check)validateSchema(schema)— Validates a complete schema definition object
Constants
FIELD_TYPES— Valid schema field types:'string','integer','float','boolean','json','datetime','time'RESERVED_FIELD_NAMES— Reserved field names:'model','schema'IDENTIFIER_PATTERN— Regex:/^[a-zA-Z_][a-zA-Z0-9_]*$/
Helpers
coerceBooleans(record)— Convertstrue/falseto1/0in a record (SQLite compatibility; applied automatically bycreateRecordandupdateRecord)buildQueryString(params)— Builds a URL query string from an object
Features
- Boolean coercion —
createRecordandupdateRecordautomatically convert JavaScript booleans to1/0for SQLite compatibility. On read, the server coerces0/1back totrue/false, so you always work with native booleans. - JSON field support — The sqlcrud server automatically serializes objects and arrays to JSON strings on write and deserializes them on read. Send native JavaScript objects and arrays directly — no manual
JSON.stringify/JSON.parseneeded. - Composite primary keys — Schemas may define multiple fields with
primary: true; the server creates composite primary key constraints automatically. - Empty query results —
queryRecordsreturns an empty array ([]) when no records match, rather than throwing aSqlCrudNotFoundError. - Query parameter building — Record query methods build and encode URL query parameters automatically.
- Basic Auth — Credentials from the constructor are sent as
Authorization: Basicon every request. - No dependencies — Uses native
fetch(Node.js 18+, all modern browsers).
TypeScript
Type definitions are included. Import normally — your TypeScript compiler will pick up types.d.ts automatically via the exports field in package.json.
import { SqlCrudClient, SchemaDefinition, SqlCrudError } from 'sqlcrud-client';Requirements
- Node.js >= 18.0.0 or any modern browser with
fetchsupport
