Skip to content

Commit

Permalink
Merge pull request #286 from appwrite/feat-node-databases
Browse files Browse the repository at this point in the history
Feat: Node Database templates
  • Loading branch information
christyjacob4 authored May 23, 2024
2 parents a535541 + 234c8aa commit 5b3728e
Show file tree
Hide file tree
Showing 30 changed files with 1,382 additions and 0 deletions.
50 changes: 50 additions & 0 deletions node/query-mongo-atlas/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# 🗄️ Node.js Query Mongo Atlas Function

A function to store warehouses to SQL database, and query to list them.

## 🧰 Usage

### GET /

- Save one warehouse and query to return all of them.

**Response**

Sample `200` Response:

```js
[
{
"_id": "664897aff5fc199b80c1a132",
"location": "Street 283, Earth",
"capacity": 60
},
{
"_id": "664897f58f2d686e85b93692",
"location": "Street 593, Earth",
"capacity": 60
},
// ...
]
```

## ⚙️ Configuration

| Setting | Value |
| ----------------- | ------------- |
| Runtime | Node (18.0) |
| Entrypoint | `src/main.js` |
| Build Commands | `npm install` |
| Permissions | `any` |
| Timeout (Seconds) | 15 |

## 🔒 Environment Variables

### MONGO_URI

The endpoint to connect to your Mongo database.

| Question | Answer |
| ------------ | ------------------------------ |
| Required | Yes |
| Sample Value | `mongodb+srv://appwrite:[email protected]/?retryWrites=true&w=majority&appName=Appwrite` |
151 changes: 151 additions & 0 deletions node/query-mongo-atlas/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions node/query-mongo-atlas/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "query-mongo-atlas",
"version": "1.0.0",
"main": "src/main.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"mongodb": "^6.6.2"
}
}
25 changes: 25 additions & 0 deletions node/query-mongo-atlas/src/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { throwIfMissing } from "./utils.js";
import { getClient, insertTestData, listWarehouses } from "./mongo.js";

/**
* Global connection. Reused between executions
*/
let client;

export default async ({ req, res, log, error }) => {
throwIfMissing(process.env, ['MONGO_URI']);

if(req.method !== 'GET') {
return res.send('Not found.', 404);
}

if (!client) {
client = await getClient();
}

await insertTestData(client);

const warehouses = await listWarehouses(client);

return res.json(warehouses);
}
46 changes: 46 additions & 0 deletions node/query-mongo-atlas/src/mongo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { MongoClient, ServerApiVersion } from 'mongodb';

/**
* Throws an error if any of the keys are missing from the object
*/
export async function getClient() {
const client = new MongoClient(process.env.MONGO_URI, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
});

await client.connect();

return client;
}

/**
* Insert a sample warehouse
*/
export async function insertTestData(client) {
const location = `Street ${Math.round(Math.random() * 1000)}, Earth`; // Random address
const capacity = 10 + Math.round(Math.random() * 10) * 10; // Random number: 10,20,30,...,90,100

await client.db("main").collection("warehouses").insertOne({
location,
capacity
});
}

/**
* Get all warehouses
*/
export async function listWarehouses(client, page = 1) {
const limit = 100;
const cursor = client.db("main").collection("warehouses").find().limit(limit).skip((page - 1) * limit);

const documents = [];
for await (const doc of cursor) {
documents.push(doc);
}

return documents;
}
14 changes: 14 additions & 0 deletions node/query-mongo-atlas/src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Throws an error if any of the keys are missing from the object
*/
export function throwIfMissing(obj, keys) {
const missing = [];
for (let key of keys) {
if (!(key in obj) || !obj[key]) {
missing.push(key);
}
}
if (missing.length > 0) {
throw new Error(`Missing required fields: ${missing.join(', ')}`);
}
}
Loading

0 comments on commit 5b3728e

Please sign in to comment.