Nimbu JavaScript SDK
The Nimbu JavaScript SDK is a powerful library for working with your Nimbu data from Cloud Code. It provides a simple, object-oriented interface for querying, creating, updating, and deleting data.
What is the Nimbu JS SDK?
The Nimbu JS SDK is embedded directly in Cloud Code, giving you immediate access to:
- Nimbu.Object - Create, read, update, and delete data objects
- Nimbu.Query - Query and filter data with powerful search capabilities
- Nimbu.Customer - Manage customer accounts and authentication
- Nimbu.Collection - Work with custom content types (channels)
- Nimbu.Product - Access and manage product data
- Nimbu.Order - Work with orders and transactions
- Nimbu.File - Handle file uploads and downloads
- Nimbu.Gallery - Manage image galleries
- Nimbu.Role - Manage customer roles and permissions
Key Differences in Cloud Code
Unlike using the SDK in themes or external applications, when using it in Cloud Code:
✅ No Initialization Required
The SDK is already initialized and authenticated - just start using it:
// In Cloud Code - NO initialization needed!
const query = new Nimbu.Query('products');
const products = await query.collection().fetch();
// In themes/external apps - initialization IS required
// Nimbu.initialize('YOUR_ACCESS_TOKEN'); // Not needed in Cloud Code✅ Full Server-Side Access
Cloud Code has unrestricted access to your data:
// Access any data without authentication restrictions
const customers = await new Nimbu.Query('customers').collection().fetch();
// Modify system fields and perform admin operations
customer.set('loyalty_points', 1000);
await customer.save();✅ Async/Await Support
Use modern async/await syntax throughout:
Nimbu.Cloud.job('myJob', async () => {
const products = await new Nimbu.Query('products').collection().fetch();
for (const product of products) {
await product.save();
}
});Quick Start Examples
Creating Data
// Create a new channel entry
const entry = new Nimbu.Object('blog');
entry.set('title', 'My First Post');
entry.set('content', 'Hello World!');
entry.set('published', true);
await entry.save();
console.log('Created entry:', entry.id);Querying Data
// Find published blog posts
const query = new Nimbu.Query('blog');
query.equalTo('published', true);
query.descending('created_at');
query.limit(10);
const posts = await query.collection().fetch();
console.log(`Found ${posts.length} posts`);Updating Data
// Update an existing object
const product = await new Nimbu.Query('products').get('product_id');
product.set('price', 29.99);
product.set('stock', 100);
await product.save();Deleting Data
// Delete an object
const entry = await new Nimbu.Query('blog').get('entry_id');
await entry.destroy();Working with Customers
// Find a customer by email
const query = new Nimbu.Query('customers');
query.equalTo('email', '[email protected]');
const customer = await query.first();
if (customer) {
// Update customer data
customer.set('loyalty_points', 100);
await customer.save();
}Working with Relations
// Create objects with relationships
const author = new Nimbu.Object('authors');
author.set('name', 'John Doe');
await author.save();
const book = new Nimbu.Object('books');
book.set('title', 'My Book');
book.set('author', author); // Set relationship
await book.save();
// Query with included relations
const query = new Nimbu.Query('books');
query.include('author');
const books = await query.collection().fetch();
books.forEach(book => {
const author = book.get('author');
console.log(`${book.get('title')} by ${author.get('name')}`);
});Main SDK Classes
Core Classes
- Nimbu.Object - Base class for all data objects
- Nimbu.Query - Query and filter data
Specialized Classes
- Customer - Customer accounts
- Collection - Custom content types
- Product - E-commerce products
- Order - Customer orders
- File - File uploads
- Gallery - Image galleries
- Role - Customer roles
Common Patterns
Batch Operations
// Process items in batches
const query = new Nimbu.Query('products');
query.equalTo('active', true);
const products = await query.collection().fetch();
for (const product of products) {
product.set('updated_at', new Date());
await product.save();
}Conditional Updates
// Update only if condition is met
const order = await new Nimbu.Query('orders').get(orderId);
if (order.get('status') === 'pending') {
order.set('status', 'processing');
await order.save();
}Error Handling
try {
const product = await new Nimbu.Query('products').get(productId);
product.set('price', newPrice);
await product.save();
} catch (error) {
console.error('Failed to update product:', error.message);
// Handle error appropriately
}Counting Results
// Get count without fetching all data
const query = new Nimbu.Query('customers');
query.equalTo('newsletter_subscribed', true);
const count = await query.count();
console.log(`${count} subscribers`);SDK vs. API
The SDK provides a higher-level, object-oriented interface compared to making direct API calls:
Using the SDK (Recommended)
const customer = new Nimbu.Object('customers');
customer.set('email', '[email protected]');
customer.set('name', 'John Doe');
await customer.save();Using Direct API Calls
const HTTP = require('http');
const response = await HTTP.post('/api/customers', {
body: JSON.stringify({
email: '[email protected]',
name: 'John Doe'
}),
headers: { 'Content-Type': 'application/json' }
});The SDK is preferred because it:
- Automatically handles authentication
- Provides better error messages
- Validates data before sending
- Handles relationships elegantly
- Offers a cleaner, more intuitive API
Promise vs. Callback Style
The SDK supports both promises and callbacks, but async/await is recommended:
Modern Async/Await (Recommended)
async function createProduct() {
const product = new Nimbu.Object('products');
product.set('name', 'Widget');
await product.save();
return product;
}Promise Style
function createProduct() {
const product = new Nimbu.Object('products');
product.set('name', 'Widget');
return product.save().then(product => {
return product;
});
}Callback Style (Not Recommended)
function createProduct(callback) {
const product = new Nimbu.Object('products');
product.set('name', 'Widget');
product.save({
success: (product) => {
callback(null, product);
},
error: (product, error) => {
callback(error);
}
});
}Best Practices
1. Use Async/Await
// Good
const product = await query.first();
await product.save();
// Avoid
query.first().then(product => {
product.save().then(() => {
// Nested promises...
});
});2. Handle Errors
// Good
try {
await object.save();
} catch (error) {
console.error('Save failed:', error.message);
}
// Avoid
await object.save(); // Unhandled errors will crash3. Use Includes for Relations
// Good - One query with includes
const query = new Nimbu.Query('books');
query.include('author');
const books = await query.collection().fetch();
// Avoid - N+1 queries
const books = await query.collection().fetch();
for (const book of books) {
const author = await book.get('author').fetch();
}4. Limit Query Results
// Good
query.limit(100);
const results = await query.collection().fetch();
// Avoid
const results = await query.collection().fetch(); // Could be thousands!5. Use Specific Queries
// Good
query.equalTo('status', 'active');
query.equalTo('category', 'books');
// Avoid
const all = await query.collection().fetch();
const filtered = all.filter(item =>
item.get('status') === 'active' &&
item.get('category') === 'books'
);SDK Structure
The SDK is organized around these key concepts:
Nimbu
├── Object - Base class for all data
│ ├── extend() - Create subclasses
│ ├── save() - Persist changes
│ ├── destroy() - Delete object
│ ├── get() - Get attribute value
│ └── set() - Set attribute value
│
├── Query - Query and filter data
│ ├── equalTo() - Filter by value
│ ├── find() - Execute query
│ ├── first() - Get first result
│ ├── count() - Count results
│ └── include() - Include relations
│
├── Customer - Customer-specific methods
├── Collection - Collection utilities
├── Product - Product helpers
├── Order - Order management
├── File - File handling
├── Gallery - Gallery management
└── Role - Role managementNext Steps
Learn more about specific SDK classes:
- Nimbu.Object - Working with data objects
- Nimbu.Query - Querying and filtering data
- Other Classes - Customer, Product, Order, File, etc.
Or explore Cloud Code features:
- Callbacks - React to data changes
- Cloud Functions - Callable server functions
- Background Jobs - Scheduled tasks
- Routes - HTTP endpoints