{"library":"s3db.js","title":"s3db.js: S3 Document Database ORM","description":"s3db.js transforms AWS S3 into a powerful, cost-effective document database by leveraging S3's metadata capabilities to store document data up to 2KB per object, providing a serverless ORM-like interface. Currently at version 21.6.2, the library maintains an active release cadence with frequent patch and minor updates, indicating ongoing development and feature expansion. It differentiates itself by offering automatic encryption, schema validation, a streaming API for efficient data handling, and an extensive plugin architecture that supports multi-backend operations, including `RedDBClient` and integration with various other AWS services and external databases. Designed for serverless applications, cost-conscious projects, and rapid prototyping, it aims to reduce database management overhead. While its core leverages S3 for storage, its `DatabaseManager` allows integration with alternative storage backends and services, making it a flexible solution for diverse cloud data needs.","language":"javascript","status":"active","last_verified":"Wed Apr 22","install":{"commands":["npm install s3db.js"],"cli":{"name":"s3db","version":null}},"imports":["import { DatabaseManager } from 's3db.js';","import { Model } from 's3db.js';","import { Field } from 's3db.js';"],"auth":{"required":false,"env_vars":[]},"quickstart":{"code":"import { DatabaseManager, Model, Field } from 's3db.js';\nimport { S3Client } from '@aws-sdk/client-s3';\n\n// Initialize AWS S3 Client with credentials from environment variables\nconst s3Client = new S3Client({\n  region: process.env.AWS_REGION ?? 'us-east-1',\n  credentials: {\n    accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? '', \n    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? '',\n  },\n});\n\n// Configure DatabaseManager for the S3 backend\nconst dbManager = new DatabaseManager({\n  backends: {\n    s3: {\n      type: 's3',\n      client: s3Client,\n      bucketName: process.env.S3_BUCKET_NAME ?? 'my-s3db-test-bucket',\n      prefix: 'my-app-data/', // Optional: prefix for keys within the bucket\n    },\n  },\n  defaultBackend: 's3',\n});\n\n// Define a User Model with a schema\nclass User extends Model {\n  static schema = {\n    id: Field.id(), // Primary key\n    name: Field.string({ required: true, maxLength: 100 }),\n    email: Field.string({ required: true, unique: true, validator: (v: string) => v.includes('@') }),\n    age: Field.number({ min: 18, max: 120, optional: true }),\n    isActive: Field.boolean({ default: true }),\n    createdAt: Field.timestamp({ auto: true }),\n  };\n\n  constructor(data?: any, options?: any) {\n    super(data, { ...options, dbManager, backend: 's3' });\n  }\n}\n\nasync function runS3DBExample() {\n  // Ensure S3 bucket exists and credentials are valid.\n  await dbManager.connect();\n  console.log('Connected to S3DB backend.');\n\n  try {\n    // 1. Create a new user\n    const newUser = new User({\n      name: 'Alice Wonderland',\n      email: 'alice@example.com',\n      age: 30,\n    });\n    const createdUser = await newUser.insert();\n    console.log('Created User:', createdUser.toObject());\n\n    // 2. Find a user by ID\n    const foundUser = await User.findById(createdUser.id); // Static method for finding by ID\n    if (foundUser) {\n      console.log('Found User by ID:', foundUser.toObject());\n\n      // 3. Update the user\n      foundUser.age = 31;\n      foundUser.isActive = false;\n      const updatedUser = await foundUser.update();\n      console.log('Updated User:', updatedUser.toObject());\n    }\n\n    // 4. List all users (note: for S3 metadata, complex queries might involve scanning)\n    const allUsers = await User.findMany({}); // Fetches all documents under the model's prefix\n    console.log(`Total users found: ${allUsers.length}`);\n    if (allUsers.length > 0) {\n      console.log('First user from findMany:', allUsers[0].toObject());\n    }\n\n    // 5. Delete the user\n    if (foundUser) {\n      await foundUser.delete();\n      console.log(`Deleted User with ID: ${foundUser.id}`);\n    }\n\n  } catch (error) {\n    console.error('Error during S3DB operations:', error);\n  } finally {\n    // In S3's stateless nature, explicit disconnects are often not needed, \n    // but a manager might offer a cleanup method.\n  }\n}\n\nrunS3DBExample();","lang":"typescript","description":"This quickstart demonstrates how to initialize `s3db.js` with an S3 backend, define a `Model` with a schema, and perform basic CRUD operations (create, find, update, delete) on document data.","tag":null,"tag_description":null,"last_tested":null,"results":[]},"compatibility":null}