A scalable, database-agnostic API designed to replace the MongoDB Data API endpoint with a SQL backend. This project allows you to interact with SQL databases (e.g., PostgreSQL, MySQL, SQLite, D1) using a MongoDB-like API. Itβs built to work with Cloudflare Workers, Hono, and D1, but can be adapted to other backend environments and databases.
- MongoDB Data API Compatibility: Replace the MongoDB Data API with a SQL-based backend.
- Database Agnostic: Works with any SQL database (PostgreSQL, MySQL, SQLite, D1, etc.).
- Scalable: Designed for serverless environments like Cloudflare Workers.
- Easy to Use: Simple and consistent API endpoints for CRUD operations.
- Validation: Ensures all required fields are present in requests.
- Error Handling: Provides detailed error messages for debugging.
| Endpoint | Description | Example Request Body |
|---|---|---|
POST /find |
Fetch multiple documents. | { "database": "db", "collection": "users", "filter": { "age": 25 } } |
POST /findOne |
Fetch a single document. | { "database": "db", "collection": "users", "filter": { "id": 1 } } |
POST /insertOne |
Insert a single document. | { "database": "db", "collection": "users", "document": { "name": "John", "age": 30 } } |
POST /insertMany |
Insert multiple documents. | { "database": "db", "collection": "users", "documents": [{ "name": "John" }, { "name": "Jane" }] } |
POST /updateOne |
Update a single document. | { "database": "db", "collection": "users", "filter": { "id": 1 }, "update": { "age": 31 } } |
POST /updateMany |
Update multiple documents. | { "database": "db", "collection": "users", "filter": { "age": 30 }, "update": { "age": 31 } } |
POST /deleteOne |
Delete a single document. | { "database": "db", "collection": "users", "filter": { "id": 1 } } |
POST /deleteMany |
Delete multiple documents. | { "database": "db", "collection": "users", "filter": { "age": 30 } } |
POST /aggregate |
Perform aggregation operations. | { "database": "db", "collection": "users", "pipeline": [{ "$match": { "age": 25 } }] } |
To get started with this project, you'll need to have Node.js and Wrangler installed.
- Clone the repository:
git clone https://github.com/your-username/mongodb-to-sql-adapter-api.git cd mongodb-to-sql-adapter-api - Install the dependencies:
npm install
- Configure your database: See the "Configuration" section for more details.
- Run the project locally:
npm start
- Deploy the project:
npm run deploy
This project is a drop-in replacement for the MongoDB Data API endpoint. If youβre migrating from MongoDB to a SQL database, this API allows you to keep your existing client code while switching to a SQL backend.
The API is designed to work with any SQL database. Whether youβre using PostgreSQL, MySQL, SQLite, or Cloudflareβs D1, you can easily adapt this project to your needs.
Built for Cloudflare Workers and Hono, this API is lightweight, fast, and scalable. Itβs perfect for serverless environments where performance and cost-efficiency are critical.
The modular design makes it easy to add new features or support additional databases. The database service layer abstracts all database operations, so you only need to implement the logic once.
Before you begin, ensure you have the following installed:
-
Node.js: Download and install Node.js.
-
Wrangler: Cloudflareβs CLI for deploying Workers. Install it globally:
npm install -g wrangler
-
Git: Download and install Git.
Clone the repository to your local machine:
git clone https://github.com/Vgshots/mongodb-to-sql-adapter-api.git
cd mongodb-to-sql-adapter-apiInstall the required dependencies:
npm installAuthenticate Wrangler with your Cloudflare account:
wrangler loginCreate a new D1 database:
wrangler d1 create my-databaseThis will output something like:
β
Successfully created DB 'my-database' in region 'auto'
Created your database using D1's new storage backend. The new storage backend is not yet recommended for production workloads, but backs up your data by default.
Database ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Take note of the Database ID (youβll need it in the next step).
Open the wrangler.toml file and add the D1 database configuration:
[[d1_databases]]
binding = "DB" # The name you'll use to access the database in your Worker
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # Replace with your Database IDYou need to create tables in your D1 database to match the collections youβll use in the API. For example, to create a users table:
-
Open the D1 database shell:
wrangler d1 execute my-database --local --file=./schema.sql
-
Create a
schema.sqlfile with the following content:CREATE TABLE users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER );
-
Run the schema file to create the table:
wrangler d1 execute my-database --local --file=./schema.sql
Deploy the project to Cloudflare Workers:
wrangler deploymongodb-to-sql-adapter-api/
βββ config/
β βββ config.js # Configuration file
βββ middleware/
β βββ auth.js # API key authentication middleware
β βββ logging.js # Logging middleware
βββ routes/
β βββ aggregate.js # Aggregate endpoint
β βββ apiRoutes.js # All API routes
β βββ delete.js # Delete endpoints
β βββ find.js # Find endpoints
β βββ insert.js # Insert endpoints
β βββ update.js # Update endpoints
βββ services/
β βββ d1Adapter.js # D1 database adapter
β βββ databaseService.js # Database service
βββ tests/
β βββ find.test.js # Tests for the find endpoint
βββ utils/
β βββ errorHandler.js # Error handler
β βββ httpError.js # HttpError class
β βββ queryBuilder.js # Query builder
βββ .gitignore # Git ignore file
βββ README.md # Project documentation
βββ index.js # Entry point
βββ instructions.js # Instructions
βββ package-lock.json # Package lock file
βββ package.json # Package file
βββ wrangler.toml # Wrangler configuration
- A request is made to the API (e.g.,
/app/data-test/endpoint/data/v1/action/find). - The
index.jsfile routes the request to the appropriate handler in theroutes/folder. - The route handler uses the
DatabaseServiceto interact with the database. - The response is sent back to the client.
The DatabaseService abstracts all database operations (e.g., find, insert, update, delete, aggregate). It uses a database adapter to interact with the database, which makes it easy to add support for other databases in the future.
The errorHandler.js utility ensures consistent error responses and validates required fields in the request body.
The API provides detailed error messages for debugging. For example:
-
Missing Required Fields:
{ "success": false, "error": "Missing required fields: database, collection, filter" } -
Database Error:
{ "success": false, "error": "Failed to fetch documents", "details": "Error: Connection timeout" }
-
Install Wrangler:
npm install -g wrangler
-
Authenticate Wrangler:
wrangler login
-
Deploy the project:
wrangler deploy
You can adapt this project to other backend environments (e.g., Node.js, Express) by replacing the database client in config/db.js.
The configuration for this project is located in the config/config.js file. This file contains the configuration for the database.
To use D1, you'll need to update the wrangler.toml file with your D1 database information.
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"To use other databases, you'll need to create a new database adapter and update the DatabaseService to use it.
This project uses vitest for testing. To run the tests, use the following command:
npm testContributions are welcome! If youβd like to contribute, please:
- Fork the repository.
- Create a new branch for your feature or bugfix.
- Submit a pull request.
This project is licensed under the MIT License. See the LICENSE file for details.
- Hono: For providing a lightweight and fast framework for Cloudflare Workers.
- Cloudflare D1: For offering a serverless SQL database solution.
- MongoDB Data API: For inspiring this project as a replacement.
If you have any questions or need help, feel free to reach out:
- Email: hassan02939@gmail.com
- GitHub Issues: Create an issue
Made with β€οΈ by Vgshots
-
Step-by-Step D1 Database Setup:
- How to create a D1 database.
- How to bind it to your Worker.
- How to create tables using SQL schema files.
-
Testing and Verification:
- Explains how to test the API using tools like Postman or
curl.
- Explains how to test the API using tools like Postman or
-
Detailed Instructions:
- Every step is explained in detail, so even beginners can follow along.
- Comprehensive Guide: Covers everything from setup to deployment.
- Beginner-Friendly: Step-by-step instructions with explanations.
- Visual Appeal: Uses tables, code blocks, and emojis to make the README visually engaging.
- Handy for GitHub: Includes all the information a user needs to understand, use, and contribute to the project.
Let me know if you need further tweaks or additions! π