Created
December 14, 2021 07:35
-
-
Save phiniezyc/f73bf819217252daf29168abb5d99f6b to your computer and use it in GitHub Desktop.
Auth0 Action to Save User in MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const { MongoClient } = require('mongodb'); | |
| /** | |
| * Handler that will be called during the execution of a PostUserRegistration flow. | |
| * | |
| * @param {Event} event - Details about the context and user that has registered. | |
| */ | |
| exports.onExecutePostUserRegistration = async (event) => { | |
| let uri = event.secrets.MONGODB_URI; | |
| let dbName = event.secrets.MONGODB_DB; | |
| let cachedClient = null; | |
| let cachedDb = null; | |
| const { db } = await connectToDatabase(); | |
| const newUser = event.user; | |
| const result = await db.collection('user').insertOne(newUser); | |
| async function connectToDatabase() { | |
| if (cachedClient && cachedDb) { | |
| return { client: cachedClient, db: cachedDb }; | |
| } | |
| const client = await MongoClient.connect(uri, { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true, | |
| }); | |
| const db = await client.db(dbName); | |
| cachedClient = client; | |
| cachedDb = db; | |
| return { client, db }; | |
| } | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment