sappsdb
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

sappsdb

sappsdb is a TypeScript library that enables you to interact with your MongoDB API easily. It provides methods for common database operations such as find, findOne, insert, insertMany, update, and updateMany. The library is designed with TypeScript generics so that you can enforce strong typing for your documents and queries.

Features

  • Type-Safe Methods: Use TypeScript generics to type your documents and queries.
  • Simple API: Intuitive methods for performing common MongoDB operations.
  • Bun Compatible: Uses fetch for HTTP requests, which works out of the box with Bun.
  • Modular Design: Easily extendable with support for additional operations like aggregate, transactions, and geo queries.

Installation

Install the package via npm:

npm install sappsdb

or using yarn:

yarn add sappsdb

or using bun:

bun add sappsdb

Usage

First, import and initialize the SappsDB client with your API endpoint:

import { SappsDB } from 'sappsdb';

interface User {
  name: string;
  email: string;
}

interface UserQuery {
  email: string;
}

// Initialize the client with the API endpoint.
const dbClient = new SappsDB('https://api.yourdomain.com', 'token');

async function example() {
  // Find users with a specific email.
  const users = await dbClient.find<User, UserQuery>('users', { email: 'example@example.com' });
  console.log('Found Users:', users);

  // Insert a new user.
  const newUser: User = { name: 'John Doe', email: 'john@example.com' };
  const insertResult = await dbClient.insert<User>('users', newUser);
  console.log('Insert Result:', insertResult);
}

example().catch(console.error);

API Methods

find<TDocument, TQuery>(collection: string, query: TQuery): Promise<TDocument[]>

Searches for documents in the specified collection using the provided query.

findOne<TDocument, TQuery>(collection: string, query: TQuery): Promise<TDocument>

Retrieves a single document matching the query.

insert<TDocument>(collection: string, document: TDocument): Promise<any>

Inserts a new document into the specified collection.

insertMany<TDocument>(collection: string, documents: TDocument[]): Promise<any>

Inserts multiple documents into the specified collection.

update<TFilter, TUpdate>(collection: string, filter: TFilter, updateDoc: TUpdate): Promise<any>

Updates a single document matching the filter criteria.

updateMany<TFilter, TUpdate>(collection: string, filter: TFilter, updateDoc: TUpdate): Promise<any>

Updates multiple documents matching the filter criteria.

Usage

First, import and initialize the SappsDB client with your API endpoint:

import { SappsDB } from 'sappsdb';

interface User {
  name: string;
  email: string;
}

interface UserQuery {
  email: string;
}

// Initialize the client with the API endpoint.
const dbClient = new SappsDB('https://api.yourdomain.com');

async function example() {
  // Find users with a specific email.
  const users = await dbClient.find<User, UserQuery>('users', { email: 'example@example.com' });
  console.log('Found Users:', users);

  // Insert a new user.
  const newUser: User = { name: 'John Doe', email: 'john@example.com' };
  const insertResult = await dbClient.insert<User>('users', newUser);
  console.log('Insert Result:', insertResult);
}

example().catch(console.error);

Inserting Documents with a Location Field

To insert a document that includes a geolocation field, format the location using GeoJSON. For example:

interface Place {
  name: string;
  location: {
    type: 'Point';
    coordinates: number[];
  };
}

async function insertPlace() {
  const place: Place = {
    name: 'Central Park',
    location: {
      type: 'Point',
      coordinates: [-73.965355, 40.782865]
    }
  };

  const result = await dbClient.insert<Place>('places', place);
  console.log('Place Inserted:', result);
}

insertPlace().catch(console.error);

Performing Advanced Geo Queries

The geo method allows you to perform advanced geo queries by constructing a valid MongoDB geo query object. Here are a few examples:

Polygon Query

Find documents within a specific polygon:

async function findPlacesInPolygon() {
  const polygonQuery = {
    location: {
      $geoWithin: {
        $geometry: {
          type: 'Polygon',
          coordinates: [
            [
              [-73.99756, 40.73083],
              [-73.99756, 40.741404],
              [-73.988135, 40.741404],
              [-73.988135, 40.73083],
              [-73.99756, 40.73083]
            ]
          ]
        }
      }
    }
  };

  const places = await dbClient.geo('places', polygonQuery);
  console.log('Places within polygon:', places);
}

findPlacesInPolygon().catch(console.error);

Near Query with Distance Constraints

Find documents near a point with minimum and maximum distances:

async function findPlacesNearby() {
  const nearQuery = {
    location: {
      $near: {
        $geometry: {
          type: 'Point',
          coordinates: [-73.99279, 40.719296]
        },
        $minDistance: 100,
        $maxDistance: 1000
      }
    }
  };

  const nearbyPlaces = await dbClient.geo('places', nearQuery);
  console.log('Nearby Places:', nearbyPlaces);
}

findPlacesNearby().catch(console.error);

Index Management

Creating an Index

You can create an index on a collection. For example, to create a unique index on the email field or a 2dsphere index on the location field:

async function createIndexes() {
  // Create a unique index on the "email" field
  const uniqueIndexName = await dbClient.createIndex('users', { email: 1 }, { unique: true });
  console.log('Unique index created:', uniqueIndexName);

  // Create a 2dsphere index on the "location" field
  const geoIndexName = await dbClient.createIndex('places', { location: "2dsphere" });
  console.log('Geo index created:', geoIndexName);
}

createIndexes().catch(console.error);

Listing Indexes

To list all indexes on a collection:

async function listIndexes() {
  const indexes = await dbClient.listIndexes('users');
  console.log('Indexes on users collection:', indexes);
}

listIndexes().catch(console.error);

Dropping an Index

To drop an index by its name:

async function dropIndex() {
  const result = await dbClient.dropIndex('users', 'email_1'); // e.g., index name "email_1"
  console.log('Index dropped:', result);
}

dropIndex().catch(console.error);

Extending the Library

The library is designed to be modular and can be extended with additional methods such as aggregate queries, transactions, and geo queries following the same pattern as the existing methods.

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests for improvements.

License

MIT License


Readme

Keywords

Package Sidebar

Install

npm i sappsdb

Weekly Downloads

5

Version

0.1.4

License

MIT

Unpacked Size

15.2 kB

Total Files

5

Last publish

Collaborators

  • sappsdev