Gathering detailed insights and metrics for @taskless/mongo-data-api
Gathering detailed insights and metrics for @taskless/mongo-data-api
Gathering detailed insights and metrics for @taskless/mongo-data-api
Gathering detailed insights and metrics for @taskless/mongo-data-api
🌿🕸️ Mongo Data API client using fetch, suitable for lambda and edge functions
npm install @taskless/mongo-data-api
Typescript
Module System
Min. Node Version
Node Version
NPM Version
TypeScript (95.38%)
JavaScript (4.14%)
Shell (0.48%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
3 Stars
38 Commits
2 Watchers
2 Branches
1 Contributors
Updated on Dec 25, 2024
Latest Version
0.5.2
Package Id
@taskless/mongo-data-api@0.5.2
Unpacked Size
96.84 kB
Size
18.49 kB
File Count
11
NPM Version
8.19.2
Node Version
18.12.1
Published on
Dec 14, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
A Mongo-like API for accessing the http-based Mongo Data API. Uses BSON to provide access to standard Mongo data types. BYO
fetch()
for maximum portability.
1import { MongoClient } from "@taskless/mongo-data-api";
2
3const mc = new MongoClient({
4 /** @type URL | string */
5 endpoint: new URL(process.env.MONGO_HTTP_URL ?? "[not defined]"),
6 /** @type string */
7 dataSource: process.env.MONGO_HTTP_DATA_SOURCE ?? "[not defined]",
8
9 /* See "Authentication" below */
10 auth: {
11 /* ... */
12 },
13});
14
15const { data, error } = await mc.findOne({
16 /* good 'ole mongo! See the Collection Methods for what's available */
17});
Authentication Method | Supported |
---|---|
API Key | ✅ |
Email & Password | ✅ |
Custom JWT | ✅ |
Bearer | ⚠️ |
1{ 2 // ... 3 auth: { 4 /** @type string */ 5 apiKey: process.env.MONGO_HTTP_API_KEY ?? "[not defined]", 6 }, 7}
1{ 2 // ... 3 auth: { 4 /** @type string */ 5 email: process.env.MONGO_EMAIL ?? "", 6 /** @type string */ 7 password: process.env.MONGO_PASSWORD ?? "", 8 }, 9}
1{ 2 // ... 3 auth: { 4 /** @type string */ 5 jwtTokenString: request.headers.get("jwt"), 6 }, 7}
Read more about authenticating Realm users in the browser
1{ 2 // ... 3 auth: { 4 /** @type string */ 5 bearerToken: tokenFromRealm, 6 }, 7}
1const client = new MongoClient(options);
options
- MongoClient options
options.endpoint
- string | URL
an endpoint for sending requests to. Your Data API Endpoint is available at your Mongo Data API UI https://cloud.mongodb.com/v2/<projectId>#/dataAPI
, where <projectId>
is your project ID. A single Data API is usable for the entire project, with individual data sources routing to specific atlas instances.options.dataSource
- string
the Data Source
for your Data API. On the Data API UI, this is the "Data Source" column, and usually is either a 1:1 mapping of your cluster name, or the default mongodb-atlas
if you enabled Data API through the Atlas Admin UI.options.auth
- AuthOptions
one of the authentication methods, either api key, email & password, or a custom JWT string. At this time, only Credential Authentication is supported.options.fetch?
- A custom fetch
function conforming to the native fetch API. We recommend cross-fetch, as it asserts a complaint fetch()
interface and avoids you having to do fetch: _fetch as typeof fetch
to satisfy the TypeScript compiler1const db = client.db(databaseName);
databaseName
- string
the name of the database to connect to1const collection = db.collection<TSchema>(collectionName);
collectionName
- string
the name of the collection to connect to<TSchema>
- generic A Type or Interface that describes the documents in this collection. Defaults to the generic MongoDB Document
typeThe following Data API resources are supported
resource | support |
---|---|
findOne | ✅ |
find | ✅ |
insertOne | ✅ |
insertMany | ✅ |
updateOne | ✅ |
updateMany | ✅ |
replaceOne | ✅ |
deleteOne | ✅ |
deleteMany | ✅ |
aggregate | ✅ |
Should Data API add support for other resources, the callApi
method allows you to pass arbitrary JSON to a Data API resource. mongo-data-api
automatically merges the dataSource
, database
, and collection
parameters in if not specified.
All collection methods return an object containing data?
and error?
. This avoids throwing during requests, making it easier to handle the response without nesting try/catch operations.
1interface DataAPIResponse { 2 data?: TSchema; 3 error?: DataAPIError; 4}
To help with tracing and debugging, any Mongo Data API operation can be named by passing a string as the first parameter. This value is converted to the x-realm-op-name
header and can be seen in the Mongo Data API logs.
1const { data, error } = await collection./*operation*/("operation name for tracing", filter, options);
1const { data, error } = await collection.findOne(filter, options);
filter?
- Filter<TSchema>
A MongoDB Query Filteroptions?
- Query options
options.projection?
- Document
A MongoDB Query Projection1const { data, error } = await collection.find(filter, options);
filter?
- Filter<TSchema>
A MongoDB Query Filteroptions?
Query options
options.projection?
- Document
A MongoDB Query Projectionoptions.sort?
- Sort
A MongoDB Sort Expressionoptions.limit?
- number
The maximum number of matched documents to include in the returned result set. Each request may return up to 50,000 documents.options.skip?
- number
The number of matched documents to skip before adding matched documents to the result set.1const { data, error } = await collection.insertOne(document);
document
- TSchema
The document to insert1const { data, error } = await collection.insertMany(documents);
documents
- TSchema[]
The documents to insert1const { data, error } = await collection.updateOne(filter, update, options);
filter
- Filter<TSchema>
A MongoDB Query Filterupdate
- UpdateFilter<TSchema> | Partial<TSchema>
A MongoDB Update Expression that specifies how to modify the matched documentoptions?
Query options
options.upsert
- boolean
The upsert flag only applies if no documents match the specified filter. If true, the updateOne action inserts a new document that matches the filter with the specified update applied to it.1const { data, error } = await collection.updateMany(filter, update, options);
filter
- Filter<TSchema>
A MongoDB Query Filterupdate
- UpdateFilter<TSchema> | Partial<TSchema>
A MongoDB Update Expression that specifies how to modify the matched documentoptions?
Query options
options.upsert
- boolean
The upsert flag only applies if no documents match the specified filter. If true, the updateOne action inserts a new document that matches the filter with the specified update applied to it.1const { data, error } = await collection.replaceOne( 2 filter, 3 replacement, 4 options 5);
filter
- Filter<TSchema>
A MongoDB Query Filterreplacement
- WithoutId<TSchema>
The replacement document, without an _id
attributeoptions?
Query options
options.upsert
- boolean
The upsert flag only applies if no documents match the specified filter. If true, the updateOne action inserts a new document that matches the filter with the specified update applied to it.1const { data, error } = await collection.deleteOne(filter);
filter
- Filter<TSchema>
A MongoDB Query Filter1const { data, error } = await collection.deleteMany(filter);
filter
- Filter<TSchema>
A MongoDB Query Filter1const { data, error } = await collection.aggregate<TOutput>(pipeline);
pipeline
- Document[]
A MongoDB Aggregation Pipeline<TOutput>
- generic A Document
like object that describes the output of the aggregation pipeline1const { data, error } = await collection.callApi<T>(method, body);
method
- string
A supported Mongo Data API Request methodbody
- Record<string, unknown>
An arbitrary key/value JSON-like data structure representing the body payload sent to the Mongo Data API<T>
- generic Describes the return type of data
on a successful API callRequests via fetch()
have their resposne codes checked against the Data API Error Codes and on error, set the error
property of the response to a MongoDataAPIError
.
error.code
- number
Contains the HTTP error code from the Mongo Data APIerror.message
- string
Contains the response status text or error message included from the Data API callmongodb
in the dependencies? TypeScript requires it, however, the mongodb dependency is types-only and will not be included in your built lambda when using tsc
, rollup
, webpack
, etc. You can verify that mongo is not included by looking at the CommonJS build.node-fetch
's fetch
not of the correct type? node-fetch
's fetch
isn't a true fetch
and wasn't typed as one. To work around this, you can either use cross-fetch
which types the fetch
API through a type assertion, or perform the type assertion yourself: fetch: _fetch as typeof fetch
. It's not ideal, but with proper fetch
coming to node.js, it's a small inconvienence in the short term.fetch
calls? fetch-retry
(github) is an excellent library. You can also use a lower level retry tool like p-retry
(github) if you want to manage more than just the fetch()
operation itself.This library started out as a fork of the excellent deno atlas_sdk module, optimized for node.js.
MIT
No vulnerabilities found.
No security vulnerabilities found.