Skip to content

Instantly share code, notes, and snippets.

@patarapolw
Last active October 30, 2019 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patarapolw/a181293e1f7214de78d175237e8fff4f to your computer and use it in GitHub Desktop.
Save patarapolw/a181293e1f7214de78d175237e8fff4f to your computer and use it in GitHub Desktop.
MongoDB API specification

Instead of https://github.com/TossShinHwa/node-odata

GET    /books
GET    /books(:id)
POST   /books
PUT    /books(:id)
DELETE /books(:id)

I use

POST   /books        // Read, with pagination, with default of first 10 records
POST   /books(:id)   // Read, single
PUT    /books        // Create, or update multiple
PUT    /books(:id)   // Update one
DELETE /books        // Delete multiple
DELETE /books(:id)   // Delete one

Which also support JSON body if there is no (:id) (Note: GET might ignore JSON body., so I just remove it.)

JSON request contains

interface IJsonRequest {
  $match?: string | object;  // MongoDB filter object, or string to be parse with <https://github.com/patarapolw/q2filter>
  $skip?: number;
  $limit?: number;
  $sort?: string[] | object | [string, 1 | -1][];  // I fear that JSON ordering might not be preserved, so I use [string, 1 | -1][] just like in PyMongo
  $project?: string[] | object;  // For MongoDB projection aka select in SQL
  $aggregate?: object;  // MongoDB aggregate object
}

And, JSON response contains

interface IJsonResponse {
  result?: object | object[];  // Depending on whether you request with POST /books(:id) or POST /books
  error?: string | object;
  count?: number;  // Item total count for all items in the database, for POST requests
}

I can use TypeScript definitions to declare the exact object depending on the database schema. These definition packages will be made as a @scoped NPM packages, and will need to be installed on both frontend and backend.

I still have no clue on Validation, though. Maybe instead of TypeScript, I should use a better Schema.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment