Ever needed a platform to manage your club's events? Or perhaps schedule meetings in your office? But in search of affordable platforms, you get lost in the numerous options presented to you? Or maybe you just want to organize your life better and schedule when you have to attend which events?
Follow this post through the end, and you'll end up with a basic event scheduling API where all basic features like event creation and registration will be available.
The GitHub repository for this project is at https://github.com/xerctia/gatherly
Express is a Javascript framework for setting up and building servers to handle various kinds of requests like GET, POST etc. Express is one of the most popularly used backend frameworks, and is also one of the easiest framework for beginners to start with. In this blog, we will be using Express for making our server and setting up the required endpoints.
PostgreSQL is an open-source relational database management system (RDBMS), known for its reliability, scalability, and support for complex queries. It offers advanced features like support for JSON data, full-text search, and extensibility, making it versatile for both small projects and large-scale applications. PostgreSQL is popular among developers and is valued for its robust performance.
There are many PostgreSQL providers available on the web that allow usage of a PostgreSQL database, some free of cost and some with a paid plan. In this project, we will be using Supabase and its database as our PostgreSQL.
const exp = require('express'); const cors = require('cors'); const app = exp(); const PORT = 3000 || process.env.PORT; app.use(express.json()); app.use(express.urlencoded({extended: true})); app.use(cors()); app.get("/", (req, res) => { res.send("Hello, Gatherly!"); }) app.listen(PORT, () => { console.log(`server started on ${PORT}`); })
Congrats! You have successfully set up a basic server in Express!
const exp = require('express'); const cors = require('cors'); const app = exp(); const PORT = 3000 || process.env.PORT; app.use(express.json()); app.use(express.urlencoded({extended: true})); app.use(cors()); app.get("/", (req, res) => { res.send("Hello, Gatherly!"); }) app.listen(PORT, () => { console.log(`server started on ${PORT}`); })
CREATE TABLE events ( id SERIAL PRIMARY KEY, title VARCHAR(255) NOT NULL, description TEXT, start_time TIMESTAMP NOT NULL, end_time TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
DATABASE_URL="postgresql://username:password@host:port/dbname"
const { Pool } = require('pg'); require('dotenv').config(); const pool = new Pool({ connectionString: process.env.DATABASE_URL, ssl: { rejectUnauthorized: false } }); module.exports = pool;
Congratulations, you have successfully connected your Supabase database to your index.js file. We are now ready to start building the actual API endpoints.
const exp = require('express'); const cors = require('cors'); const app = exp(); const PORT = 3000 || process.env.PORT; app.use(express.json()); app.use(express.urlencoded({extended: true})); app.use(cors()); app.get("/", (req, res) => { res.send("Hello, Gatherly!"); }) app.listen(PORT, () => { console.log(`server started on ${PORT}`); })
CREATE TABLE events ( id SERIAL PRIMARY KEY, title VARCHAR(255) NOT NULL, description TEXT, start_time TIMESTAMP NOT NULL, end_time TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
DATABASE_URL="postgresql://username:password@host:port/dbname"
const { Pool } = require('pg'); require('dotenv').config(); const pool = new Pool({ connectionString: process.env.DATABASE_URL, ssl: { rejectUnauthorized: false } }); module.exports = pool;
const pool = require('./db');
app.get('/events', async (req, res) => { // code to be written })
try { // code to be written } catch (e) { console.error(e); res.status(500).json({error: "Database error."}); // 500 = Internal Server Error }
const result = await pool.query("SELECT * FROM events");
res.status(200).json(result.rows); // 200 = OK
app.get('/events', async (req, res) => { try { // Getting all events const result = await pool.query("SELECT * FROM events"); res.status(200).json(result.rows); // 200 = OK } catch (e) { console.error(e); res.status(500).json({error: 'Database error'}); // 500 = Internal Server Error } })
app.post("/events", async (req, res) => { try { // code to be written } catch (e) { console.error(e); res.status(500).json({error: "Failed to create event."}); // 500 = Internal Server Error } })
This can also be done outside the try-catch, just like the input values in the previous endpoint.
const exp = require('express'); const cors = require('cors'); const app = exp(); const PORT = 3000 || process.env.PORT; app.use(express.json()); app.use(express.urlencoded({extended: true})); app.use(cors()); app.get("/", (req, res) => { res.send("Hello, Gatherly!"); }) app.listen(PORT, () => { console.log(`server started on ${PORT}`); })
CREATE TABLE events ( id SERIAL PRIMARY KEY, title VARCHAR(255) NOT NULL, description TEXT, start_time TIMESTAMP NOT NULL, end_time TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
DATABASE_URL="postgresql://username:password@host:port/dbname"
For implementing this feature, you will need to create a new table in Supabase first.
Go to SQL Editor and run the following query:
const { Pool } = require('pg'); require('dotenv').config(); const pool = new Pool({ connectionString: process.env.DATABASE_URL, ssl: { rejectUnauthorized: false } }); module.exports = pool;
const pool = require('./db');
app.get('/events', async (req, res) => { // code to be written })
try { // code to be written } catch (e) { console.error(e); res.status(500).json({error: "Database error."}); // 500 = Internal Server Error }
const result = await pool.query("SELECT * FROM events");
This one is a homework for you guys. (Don't be mad, if you couldn't do it even after trying, the GitHub code is always available)
A hint: You may check if the event exists in the same way as we did in POST /event/:id/register. After that, you need to write a SELECT query for registrations table to fetch all rows with the given event_id.
Similarly, you may also try and build an endpoint for deleting a particular event, like DELETE /event/:id .
Congratulations! You have successfully created your own API for scheduling events and managing user registrations. You have come a long way.
You can add more features, like adding a cron job so that events whose end_time have passed are deleted automatically.
If you liked this post, drop a like, and comment if you have any doubts or just want to chat related to this. Also follow me on LinkedIn: https://www.linkedin.com/in/amartya-chowdhury/
The above is the detailed content of Create your own Event Scheduling API using Express and Supabase. For more information, please follow other related articles on the PHP Chinese website!