Building a Node.js API with PouchDB: A Step-by-Step Guide
What is PouchDB?
PouchDB is an open-source JavaScript database library designed for creating efficient and scalable offline-first web applications. It allows you to store data locally on the client-side and synchronize it with a server-side database when a network connection is available.
Setting up Your Development Environment
To get started, create a new project directory and navigate into it using your terminal or command prompt. Then, run the following commands to create a new package.json file and install Express.js:
npm init -y
npm install express
Next, install PouchDB using the following command:
npm install pouchdb
Creating a PouchDB Database
Create a new file called db.js in your project directory and add the following code to create a new PouchDB database:
const PouchDB = require('pouchdb');
const db = new PouchDB('books');
module.exports = db;
This code creates a new PouchDB database called “books” and exports it as a module.
Implementing CRUD Endpoints
Create a new file called book.js in your project directory and add the following code to implement CRUD endpoints for your PouchDB database:
const express = require('express');
const router = express.Router();
const db = require('./db');
// Create a new book
router.post('/new', (req, res) => {
const book = req.body;
db.put(book).then(() => {
res.send("Book created successfully!");
}).catch((err) => {
res.status(500).send(`Error creating book: ${err}`);
});
});
// Get all books
router.get('/', (req, res) => {
db.allDocs({ include_docs: true }).then((response) => {
const books = response.rows.map((row) => row.doc);
res.send(books);
}).catch((err) => {
res.status(500).send(`Error getting books: ${err}`);
});
});
// Get a single book by ID
router.get('/:id', (req, res) => {
const id = req.params.id;
db.get(id).then((book) => {
res.send(book);
}).catch((err) => {
res.status(404).send(`Book not found: ${err}`);
});
});
// Update a book
router.put('/:id', (req, res) => {
const id = req.params.id;
const book = req.body;
db.get(id).then((existingBook) => {
existingBook.title = book.title;
existingBook.author = book.author;
db.put(existingBook).then(() => {
res.send("Book updated successfully!");
}).catch((err) => {
res.status(500).send(`Error updating book: ${err}`);
});
}).catch((err) => {
res.status(404).send(`Book not found: ${err}`);
});
});
// Delete a book
router.delete('/:id', (req, res) => {
const id = req.params.id;
db.get(id).then((book) => {
db.remove(book).then(() => {
res.send("Book deleted successfully!");
}).catch((err) => {
res.status(500).send(`Error deleting book: ${err}`);
});
}).catch((err) => {
res.status(404).send(`Book not found: ${err}`);
});
});
module.exports = router;
This code implements CRUD endpoints for creating, reading, updating, and deleting books in your PouchDB database.
Using the API
To use the API, start your Node.js server using the following command:
node index.js
Then, use a tool like curl or Postman to send requests to the API endpoints. For example, to create a new book, send a POST request to http://localhost:3000/books/new with a JSON body containing the book title and author:
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
}
Similarly, you can send GET requests to retrieve books, PUT requests to update books, and DELETE requests to delete books.