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

mongo-atlas-client

v1.2.0

Published

A mongo-atlas client with dependency injection for the http-client

Downloads

51

Readme

mongo-atlas-client

Find it on NPM

The need

I needed a simple way to interact with the MongoDB Atlas DATA-API using the apikey and using the mongodb types, with typescript. Additionally, I took the opportunity to learn how to publish pure ESM modules to npm.

The data you need to use it

You'll forgive me if I'll assume you don't know how to use the data-api, but I'll assume you know how to use mongodb. If you don't, you can learn it here. When you create a project, you also create a cluster (datasource) and a database. After you've done this, you'll be able to enable the data api to use the database via https request instead the directly connection to the database.

To enable the data api you have to click on the DATA API item under the SERVICES group in the left bar menu. Then, you need to click on the Create API KEY button. You'll be asked to give a name to the key and to confirm the creation. After you have to save your key somewhere safe, because you won't be able to see it again. You'll receive also the endpoint url, that you'll need to use the api.

So, the data you'll get and you'll need to use this library are:

  • the endpoint url
  • the api key
  • the datasource
  • the database

Connection data class

/**
 * ConnectionData class
 */
export class ConnectionData
{
    /**
     * The atlas data source, should be the cluster.
     */
    public dataSource: string;
    /**
     * The database to query.
     */
    public database: string;
    /**
     * The api key to use.
     */
    public apikey: string;
    /**
     * The atlas end point to use.
     */
    public atlasEndPoint: string;

    /**
     * Constructor
     * @param config the configuration for the query
     */
    constructor(config: { dataSource: string, database: string, apikey: string, atlasEndPoint: string}) {
        this.dataSource = config.dataSource;
        this.database = config.database;
        this.apikey = config.apikey;
        this.atlasEndPoint = config.atlasEndPoint;
    }
}

Dependency Injection

To allow to use your favorite http client library, when you initialize the Client class, you can pass a callback that use your http client to make the request. The callback must return a string via promise that resolve to the response body. The callback will receive:

  • the endpoint (url with the action);
  • the body;
  • the headers;
  • the stringify function for with the EJSON support;
  • the action (find, findOne, deleteOne, etc.)

Here the type request:

export type Request = (url: string, body: any, headers: any, (obj: any) => EJSON.stringify(obj), action: Actions) => Promise<string>

TO the client you can also pass a log callback, if not, it will be used the console.log function

Responses

The responses types are the same of the mongodb types from MongoDB API responses, so you can use them directly in your code.


export interface IMongoFindOneResponse<T>
{
    /**
     * The document that was found.
     */
    document: T;
}

export interface IMongoFindResponse<T>
{
    /**
     * The documents that were found.
     */
    documents: T[];
}

export interface IMongoInsertOneResponse
{
    /**
     * The identifier that was inserted.
     */
    insertedId: string;
}

export interface IMongoInsertManyResponse
{
    /**
     * The identifiers that were inserted.
     */
    insertedIds: string[];
}

export interface IMongoDeleteResponse
{
    /**
     * The number of documents that were deleted.
     */
    deletedCount: number;
}

export interface IMongoUpdateResponse
{
    /**
     * The number of documents that were matched.
     */
    matchedCount: number;
    /**
     * The number of documents that were modified.
     */
    modifiedCount: number;
    /**
     * The identifier of the document that was upserted.
     */
    upsertedId: string;
}

export interface IMongoReplaceResponse
{
    /**
     * The number of documents that were matched.
     */
    matchedCount: number;
    /**
     * The number of documents that were modified.
     */
    modifiedCount: number;
    /**
     * The identifier of the document that was upserted.
     */
    upsertedId: string;
}

Usage

The library usage is quiet simple. Check the following example:


// example user type from user collection
class User
{
    public name: string;
    public surname: string
    public age: number;
    constructor(name: string, surname: string, age: number)
    {
        this.name = name;
        this.surname = surname;
        this.age = age;
    }
}


async function example()
{
    // set the connection data
    const connectionData: ConnectionData = new ConnectionData({
        dataSource: "source",
        database: "test",
        apikey: "1234567890",
        atlasEndPoint: "endpoint"
    });
    // set the request callback with got library
    const myRequest: Request = async (url: string, body: any, headers: any, stringify: (obj: any) => string, action: string) =>
    {
        const response = await got.post(url, { body: stringify(body), headers });
        return response.body;
    };
    // create the client
    const client = new Client(connectionData, myRequest);
    // find all users with age greater than 18
    const users = await client.find<User>("users", { age: { $gt: 18 } });
    if (users)
        for (const user of users.documents)
        {
            console.log(`${user.name} ${user.surname} is ${user.age} years old`)
        }
    // create a new user
    const userToAdd = new User("John", "Doe", 21);
    // insert the user
    const insertResponse = await client.insertOne<User>("users", userToAdd);
    if (insertResponse)
        console.log(`Added user with id: ${insertResponse.insertedId}`);

}

In this example you can see the use of the library.

  1. We start defining the connection data;
  2. Then we define the request callback, that use the got library to make the request (but you can use whatever you want).
  3. Then we create the client and we use it to find all the users with age greater than 18.
  4. Then we create a new user and we insert it in the database.

As you can see, the library support the MongoDB filters and for the response it use the MongoDB response types.

NOTE ⚠️

This isn't a library for the API of MONGO ATLAS Platform, this library is for the MONGO ATLAS DATA API