Skip to content

Commit

Permalink
Add Netlify serverless functions for adding/retrieving lists (#10)
Browse files Browse the repository at this point in the history
* Add Netlify serverless functions for adding and retrieving a list from MongoDB

* Added randomstring node module as a dependency

* Added MongoDB as a dependency
  • Loading branch information
villanovachile authored Mar 13, 2023
1 parent f2447ee commit ccb88cb
Show file tree
Hide file tree
Showing 5 changed files with 383 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
.env.development.local
.env.test.local
.env.production.local
.env

npm-debug.log*
yarn-debug.log*
Expand Down
34 changes: 34 additions & 0 deletions netlify/functions/add_list/add_list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const { MongoClient } = require("mongodb");
const randomstring = require("randomstring");

const mongoClient = new MongoClient(process.env.MONGODB_URI);

const clientPromise = mongoClient.connect();

const handler = async (event) => {
const input = JSON.parse(event.body);

const database = (await clientPromise).db(process.env.MONGODB_DATABASE);
const collection = database.collection(process.env.MONGODB_COLLECTION);
let newURI = randomstring.generate(8);
try {
await collection.insertOne({
[newURI]: input.items,
views: 0,
rating: 0,
title: input.title,
type: input.type,
unlisted: input.unlisted,
tags: input.tags,
});

return {
statusCode: 200,
body: JSON.stringify(newURI),
};
} catch (error) {
return { statusCode: 500, body: error.toString() };
}
};

module.exports = { handler };
41 changes: 41 additions & 0 deletions netlify/functions/get_list/get_list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const { MongoClient } = require("mongodb");

const mongoClient = new MongoClient(process.env.MONGODB_URI);

const clientPromise = mongoClient.connect();

const handler = async (event) => {
const input = event.queryStringParameters.uri;
try {
const database = (await clientPromise).db(process.env.MONGODB_DATABASE);
const collection = database.collection(process.env.MONGODB_COLLECTION);
const results = await collection
.find({ [input]: { $exists: true } })
.toArray();
if (results.length > 0) {
let viewCount = results[0].views;
collection.updateOne(
{ [input]: { $exists: true } },
{
$set: {
views: viewCount + 1,
},
}
);

return {
statusCode: 200,
body: JSON.stringify(results[0]),
};
} else {
return {
statusCode: 200,
body: JSON.stringify("not_found"),
};
}
} catch (error) {
return { statusCode: 500, body: error.toString() };
}
};

module.exports = { handler };
Loading

0 comments on commit ccb88cb

Please sign in to comment.