npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@hiotlabs/hiot-mongodb

v0.1.1

Published

mongo db interface for Hiotlabs services

Downloads

251

Readme

hiot-mongodb

connectToDb

Function for connecting to a mongodb database. It returns a promise that resolves to a Db object. If a locator is provided, it will add the db to the locator object. Can be used to connect to multiple databases.

interface ConnectOptions {
  host: string;
  port: number | string;
  database: string;
  replicaSet?: string;
  logger: LoggerLike;
  /** Optional if connecting to additional databases. Will add the db to the locator object if provided */
  locator?: Locator;
  /* Optional if database needs to be accessed from somewhere in the code, defaults to the database name */
  databaseIdentifier?: string;
}

function connectToDb(options: ConnectOptions): Promise<Db>;

Usage

const db = await connectToDb({
  host: "localhost",
  port: 27017,
  database: "test",
  logger,
  locator,
});

connectToDb returns the Db for the connected database. If needed, it can also be retrieved using the getDatabase function. The repository class uses getDatabase internally to get the database when needed (if a database identifier (e.g. database name) is provided).

/** @param databaseIdentifier - database identifier, defaults to name of the database */
function getDatabase(databaseIdentifier: string): Db;

const db = getDatabase("test");

To close the database connect, use the closeDbs function.

function closeDbs(): Promise<void>;

Repository

A class that provides a simple interface for interacting with a mongodb collection. Fully typed and supports all CRUD operations. It can be extended if needed (most likely not). It adds authorization to the query if a user is provided. This functionality is done by its getAuthQuery function, which can be overriden if needed. It can connect to a database using a database identifier or a Db object (e.g. if the database is connected using connectToDb in app.ts using configs, the same configs can be used as the database identifier).

constructor Repository<T>(databaseIdentifierOrDb: string | Db, collectionName: string, clazz?: (new (...args: any[]) => T) | undefined): Repository<T>

Usage

const usersRepo = new Repository("accounts-api", "users", User);
const user = await usersRepo.getById("123");

// ... or

class UsersRepo extends Repository<User> {
  constructor() {
    super("accounts-api", "users", User);
  }
}

const usersRepo = new UsersRepo();
const user = await usersRepo.asUser(req.user).getById("123");

// .. or

const usersRepo = new Repository(accountsDb, "users", User);
const user = await usersRepo.asUser(req.user).getById("123");

Functions:

save(entity: T, user?: ReqUser): Promise<T>

saveMany(entities: T[], user?: ReqUser): Promise<T[] | null>

getById(id: string, user?: ReqUser): Promise<T | null>

getByQuery(query: any, sort?: any, size?: number | undefined, page?: number | undefined, user?: ReqUser): Promise<T[]>

getTotalCount(query: any, user?: ReqUser): Promise<number>

getByQueryWithTotalCount(query: any, sort?: any, size?: number, page?: number, user?: ReqUser): Promise<{ totalCount: number; data: T[]; }>

update(id: string, entity: DeepPartial<T>, user?: ReqUser): Promise<T | null>

remove(id: string, user?: ReqUser): Promise<boolean>

removeByQuery(query: any, user?: ReqUser): Promise<boolean>

/** exported from mongodb */
aggregate(pipeline: Object[]): AggregationCursor<any>;
aggregate(pipeline: Object[], callback: MongoCallback<any[]>): AggregationCursor<any>;
aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback<any[]>): AggregationCursor<any>;

asUser(user: ReqUser): Repository<T>

asUser function

A short hand function for running a function as a specific user (it will add the user as the last of any subsequent function call). It is mostly for code readability's sake.

const thing = await thingsRepo.asUser(req.user).getByQuery({ _id: req.params.thingId });

This is the same as doing:

const thing = await thingsRepo.getByQuery({ _id: req.params.thingId }, undefined, undefined, undefined, req.user);

Test utils

insert

Port of https://github.com/hiotlabs/hiot-mongodb-js/blob/master/lib/test/insert.js which is used in most services. It inserts data into collections.

function insert(
  db: Db | string,
  context: {
    [collectionName: string]: any[];
  }
): Promise<void>;
insert("accounts-api", {
  users: [{ _id: "123", name: "John" }],
  things: [{ _id: "456", name: "Thing" }],
});

// or

insert(accountsDb, {
  users: [{ _id: "123", name: "John" }],
  things: [{ _id: "456", name: "Thing" }],
});

getAuthQuery

When user is provided to a repository function, the getAuthQuery function does the following (if not overridden):

  • For global users

    • Returns any data matching the original query
  • For users with the ability to manage their organization (has canManageOrganization activity):

    • Returns data belonging to the user's organization
    • Returns data shared with the user's organization
  • For regular users (does not have canManageOrganization activity):

    • Returns data within the user's organization owned by the user
    • Returns data within the user's organization shared directly with the user

Running tests

Since the tests rely on mongodb, you can either run the tests using the docker-compose file provided or by running mongodb locally.

Docker-compose

docker-compose run hiot-mongodb (or run test:docker)

alternatively

docker-compose run hiot-mongodb bash && yarn t

Locally

If you have mongodb installed locally you can run the tests using the following commands:

mongod
yarn t

Building and publishing

// Install dependencies
yarn install

// Build
tsc

// Make sure tests pass (see above)

// Publish
npm publish --access public