Skip to content

Commit 0bfaee3

Browse files
authored
Merge pull request #69 from objectstack-ai/copilot/explore-sdk-frontend-use
2 parents 3197023 + 884d83a commit 0bfaee3

File tree

7 files changed

+1351
-5
lines changed

7 files changed

+1351
-5
lines changed

examples/browser/README.md

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Browser Example for @objectql/sdk
2+
3+
This example demonstrates how to use `@objectql/sdk` in different environments:
4+
5+
- **`index.html`** - Pure browser example (no build tools)
6+
- **`example-node.ts`** - Node.js/TypeScript example
7+
8+
## 🚀 Quick Start
9+
10+
### Prerequisites
11+
12+
You need a running ObjectQL server. You can start one using:
13+
14+
```bash
15+
# From the repository root
16+
cd examples/starters/hello-world
17+
npm install
18+
npm start
19+
```
20+
21+
The server will be available at `http://localhost:3000`.
22+
23+
### Running the Browser Example
24+
25+
1. **Open the HTML file directly in a browser:**
26+
27+
```bash
28+
# Open in your default browser
29+
open index.html # macOS
30+
xdg-open index.html # Linux
31+
start index.html # Windows
32+
```
33+
34+
2. **Or serve it with a simple HTTP server:**
35+
36+
```bash
37+
# Using Python
38+
python3 -m http.server 8080
39+
40+
# Using Node.js http-server
41+
npx http-server -p 8080
42+
43+
# Using PHP
44+
php -S localhost:8080
45+
```
46+
47+
Then navigate to `http://localhost:8080` in your browser.
48+
49+
### Running the Node.js Example
50+
51+
```bash
52+
# Install dependencies (if not already installed)
53+
cd ../../
54+
pnpm install
55+
56+
# Run the example
57+
cd examples/browser
58+
npx ts-node example-node.ts
59+
```
60+
61+
Or compile and run:
62+
63+
```bash
64+
npx tsc example-node.ts
65+
node example-node.js
66+
```
67+
68+
## 📋 Features Demonstrated
69+
70+
The example shows how to:
71+
72+
- ✅ Initialize `DataApiClient` and `MetadataApiClient` in the browser
73+
- ✅ List records with filtering and pagination
74+
- ✅ Get object metadata and schema
75+
- ✅ Create new records
76+
- ✅ Count records with filters
77+
- ✅ Handle errors and loading states
78+
- ✅ Works in all modern browsers (polyfill built-in!)
79+
80+
## 🌐 Browser Compatibility
81+
82+
This example works in all modern browsers:
83+
84+
- Chrome 90+
85+
- Firefox 90+
86+
- Safari 15+
87+
- Edge 90+
88+
89+
**Note:** The `@objectql/sdk` package automatically includes a polyfill for `AbortSignal.timeout()`, so it works seamlessly in older browsers without any additional configuration!
90+
91+
## 🔧 Using in Production
92+
93+
For production applications, we recommend:
94+
95+
### Option 1: Using a Module Bundler (Recommended)
96+
97+
```bash
98+
npm install @objectql/sdk @objectql/types
99+
```
100+
101+
```javascript
102+
import { DataApiClient, MetadataApiClient } from '@objectql/sdk';
103+
104+
const client = new DataApiClient({
105+
baseUrl: process.env.API_URL
106+
});
107+
```
108+
109+
### Option 2: Using ES Modules via CDN
110+
111+
```html
112+
<script type="module">
113+
import { DataApiClient } from 'https://cdn.skypack.dev/@objectql/sdk';
114+
115+
const client = new DataApiClient({
116+
baseUrl: 'https://api.example.com'
117+
});
118+
</script>
119+
```
120+
121+
### Option 3: Self-hosted ES Modules
122+
123+
After building the package, you can serve the dist files:
124+
125+
```html
126+
<script type="module">
127+
import { DataApiClient } from '/node_modules/@objectql/sdk/dist/index.js';
128+
129+
const client = new DataApiClient({
130+
baseUrl: 'http://localhost:3000'
131+
});
132+
</script>
133+
```
134+
135+
## 🔒 Security Considerations
136+
137+
When using the SDK in the browser:
138+
139+
1. **Never hardcode sensitive tokens** - Store them in environment variables or secure storage
140+
2. **Use HTTPS** in production
141+
3. **Implement CORS** properly on your ObjectQL server
142+
4. **Validate all user input** before sending to the API
143+
5. **Use Content Security Policy (CSP)** headers
144+
145+
## 📚 Additional Resources
146+
147+
- [ObjectQL SDK Documentation](../../packages/drivers/sdk/README.md)
148+
- [Client SDK API Guide](../../docs/api/client-sdk.md)
149+
- [REST API Reference](../../docs/api/rest.md)
150+
- [ObjectQL Website](https://objectql.org)
151+
152+
## 🤝 Contributing
153+
154+
Found an issue or want to improve this example? Please open an issue or submit a PR!

examples/browser/example-node.ts

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* Simple Node.js example using @objectql/sdk
3+
*
4+
* This demonstrates how to use the ObjectQL SDK in a Node.js environment.
5+
* The same code works in browsers, Deno, and edge runtimes!
6+
*/
7+
8+
import { DataApiClient, MetadataApiClient } from '@objectql/sdk';
9+
10+
// Initialize clients
11+
const dataClient = new DataApiClient({
12+
baseUrl: process.env.OBJECTQL_URL || 'http://localhost:3000',
13+
token: process.env.OBJECTQL_TOKEN // Optional authentication
14+
});
15+
16+
const metadataClient = new MetadataApiClient({
17+
baseUrl: process.env.OBJECTQL_URL || 'http://localhost:3000'
18+
});
19+
20+
async function main() {
21+
try {
22+
console.log('🚀 ObjectQL SDK Node.js Example\n');
23+
24+
// 1. List all available objects
25+
console.log('📚 Listing all objects...');
26+
const objectsResponse = await metadataClient.listObjects();
27+
console.log(`Found ${objectsResponse.items?.length || 0} objects:\n`);
28+
objectsResponse.items?.forEach(obj => {
29+
console.log(` - ${obj.name} (${obj.label})`);
30+
});
31+
32+
// 2. Get schema for a specific object (e.g., 'users')
33+
console.log('\n🔍 Getting schema for "users" object...');
34+
const userSchema = await metadataClient.getObject('users');
35+
console.log(`\nObject: ${userSchema.label}`);
36+
console.log('Fields:');
37+
Object.entries(userSchema.fields).forEach(([key, field]) => {
38+
console.log(` - ${field.name} (${field.type})${field.required ? ' *required' : ''}`);
39+
});
40+
41+
// 3. List users with filtering
42+
console.log('\n📋 Listing active users...');
43+
const usersResponse = await dataClient.list('users', {
44+
filter: [['status', '=', 'active']],
45+
sort: [['created_at', 'desc']],
46+
limit: 5
47+
});
48+
console.log(`Found ${usersResponse.items?.length || 0} active users`);
49+
usersResponse.items?.forEach(user => {
50+
console.log(` - ${user.name} (${user.email})`);
51+
});
52+
53+
// 4. Count total users
54+
console.log('\n🔢 Counting all users...');
55+
const countResponse = await dataClient.count('users');
56+
console.log(`Total users: ${countResponse.count}`);
57+
58+
// 5. Create a new user (example - commented out to avoid side effects)
59+
/*
60+
console.log('\n➕ Creating a new user...');
61+
const newUser = await dataClient.create('users', {
62+
name: 'SDK Example User',
63+
email: `sdk-example-${Date.now()}@example.com`,
64+
status: 'active'
65+
});
66+
console.log(`Created user: ${newUser.name} (ID: ${newUser._id})`);
67+
*/
68+
69+
console.log('\n✅ Example completed successfully!');
70+
} catch (error) {
71+
console.error('\n❌ Error:', error.message);
72+
73+
if (error.code) {
74+
console.error('Error code:', error.code);
75+
}
76+
77+
if (error.details) {
78+
console.error('Details:', error.details);
79+
}
80+
81+
process.exit(1);
82+
}
83+
}
84+
85+
// Run the example
86+
main();

0 commit comments

Comments
 (0)