26
loading...
This website collects cookies to deliver better user experience
Name
text field in the first column and an Email
field in the second column.npm init -y
, which automatically generates a package.json
file in the root of the project.npm install @notionhq/client
.env
file in your root directory. Copy the internal integration token we generated earlier and assign that to a NOTION_API_TOKEN
variable in your .env
file.npm i dotenv
notion.so/
and ?
.cab3c272b2f848e5ae0b85fa8dda5a1c
. Repeat the same process for the Bootcamp Mailing List workspace.NOTION_DATABASE_ID
in your .env
file. Update this variable with your Bootcamp database ID. Add another variable called NOTION_MAILING_LIST_ID
and add your Bootcamp Mailing List database ID..env
file should hold your NOTION_DATABASE_ID
, NOTION_MAILING_LIST_ID
, and NOTION_API_TOKEN
.NOTION_API_TOKEN
, NOTION_MAILING_LIST_ID
, and NOTION_DATABASE_ID
, we can begin working with the Notion SDK.|___controllers
|___bootcamp.controller.js
|___models
|___bootcamp.model.js
|___routes
|___index.js
|___services
|___notion.js
|___.env
|___server.js
controllers
: holds the business logic for our applicationmodels
: holds the code for interaction with the Notion database integrationroutes
: holds the code for routing within our applicationservices
: contains code for connecting our application to an external service like Notionservices
. In your services
directory, paste the following block of code in your notion.js
file:// In this file, we connect to the Notion Service
require('dotenv').config()
const { Client } = require('@notionhq/client');
const notion = new Client({ auth: process.env.NOTION_API_TOKEN });
module.exports = notion;
models
. The following block of code will be responsible for writing to and reading from our Notion database service:// models/bootcamp.model.js
// This file contains code to make operations on the DB
const notion = require("../services/notion");
const courseDatabaseId = process.env.NOTION_DATABASE_ID;
const mailingListDatabaseId = process.env.NOTION_MAILING_LIST_ID;
const bootcampModel = {
// list all the courses in the DB
getCourses: async () => {
try {
const { results } = await notion.databases.query({
database_id: courseDatabaseId,
});
const res = results.map((page) => {
return {
pageId: page.id,
videoURL: page.properties["YouTube Video"].url,
title: page.properties.Name.title[0].plain_text,
tags: page.properties.Tags.multi_select.map((tag) => tag.name),
summary: page.properties.Summary.rich_text[0].plain_text,
author: page.properties.Author.rich_text[0].plain_text,
startDate: page.properties.Date.date.start,
endDate: page.properties.Date.date.end,
};
});
return res;
} catch (error) {
console.error(error);
}
},
getSubscribersFromDB: async () => {
try {
const { results } = await notion.databases.query({
database_id: mailingListDatabaseId,
});
const res = results.map((page) => {
return {
name: page.properties.Name.title[0]?.text.content,
email: page.properties["E-mail"].multi_select[0]?.name,
};
});
return res;
} catch (error) {
console.error(error);
}
},
addSubscriberToDB: async ({ name, email }) => {
try {
const res = await notion.pages.create({
parent: {
database_id: mailingListDatabaseId,
},
properties: {
Name: {
title: [
{
text: { content: name, link: null },
plain_text: name,
},
],
},
"E-mail": {
multi_select: [
{
name: email,
},
],
},
},
});
return res;
} catch (error) {
return {
error: "Failed to add user to Mailing List",
};
}
},
findSubscriberByEmail: async ({ email }) => {
try {
const { results } = await notion.databases.query({
database_id: mailingListDatabaseId,
filter: {
or: [
{
property: "E-mail",
multi_select: {
contains: email,
},
},
],
},
});
// check if the results array contains a user
if (results.length > 0) {
return {
isUserInDB: true,
};
}
return {
isUserInDB: false,
};
} catch (error) {
console.error(error);
}
},
};
module.exports = bootcampModel;
models
file above, we created the findSubscriberByEmail
method, which checks if an email address already exists in our Bootcamp Mailing List.addSubscriberToDB
method adds a new user to our mailing list, and the getCourses
method returns a list of the courses in our calendar and details about each course.controllers
:// controllers/bootcamp.controller.js
// Handles the business Logic
const bootcampModel = require("../models/bootcamp.model");
const bootcampController = {
getAllCourses: async () => await bootcampModel.getCourses(),
addSubscriberToDB: async ({ name, email }) => {
const { isUserInDB } = await bootcampModel.findSubscriberByEmail({
name,
email,
});
// check if the E-mail exists
if (isUserInDB) {
return {
error: "That E-mail already exists in our mailing list.",
};
}
// if the E-mail doesn't already exist, add to Notion DB
const response = await bootcampModel.addSubscriberToDB({ name, email });
// if something goes wrong, send an error message
if (response.error) {
return {
error: response.error,
};
}
// if adding a user is successful
return { message: "Successfully added to the Bootcamp mailing list" };
},
};
module.exports = bootcampController;
controllers
. One connects to our Notion database to grab all the course details in the calendar we created on Notion, and the other adds a user to the Bootcamp Mailing List.npm i fastify
server.js
file in the root directory of your project, add the following block of code:// server.js
const fastify = require('./routes')
fastify.listen(5000, (err, address) => {
if (err) throw err
})
localhost:5000
.routes
directory you created, add the following code snippet in your index.js
file:// routes/index.js
const fastify = require("fastify")({
logger: true,
});
// Controllers
const bootcampController = require("../controllers/bootcamp.controller");
// Routes
fastify.get("/", async (req, reply) => {
try {
const res = await bootcampController.getAllCourses();
reply.type("application/json").code(200);
return { data: res };
} catch (error) {
reply.type("application/json").code(400);
return { error };
}
});
fastify.post("/", async (req, reply) => {
try {
const { name, email } = req.body;
const res = await bootcampController.addSubscriberToDB({ name, email });
reply.type("application/json").code(200);
return { data: res };
} catch (error) {
reply.type("application/json").code(400);
return { data: error };
}
});
module.exports = fastify;
routes
. The first route
accepts a GET request. The bootcampController
picks up the request, then returns the list of courses and the metadata for the courses, retrieved from our Notion database.routes
and endpoints by making requests using the REST Client extension in VS Code. Once you have REST Client installed, create a file called rest.http
in the root of your project.route
. This route
returns all the course information in our Notion database. Hit the send request button to make a GET request to localhost:5000
.route
accepts a POST request. This route
is responsible for adding a new user to the Bootcamp Mailing List and accepts Name
and Email
in the body of the request.notion-api-demo.glitch.me
endpoint. Simply replace the localhost:5000
endpoint you’re currently using inside the REST Client with my Glitch URL.