npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ferracinitec/basic-mongodb-crud

v0.1.5

Published

Create a basic CRUD for mongodb entities

Readme

BasicMongodbCrud

This repository contains a set of common utilities for creating CRUD (Create, Read, Update, Delete) routes and controllers using MongoDb with TypeScript.

Installation

$ npm install @ferracinitec/basic-mongodb-crud

Importing

import basicMongodbCrud from '@ferracinitec/basic-mongodb-crud'

or

import { CreateCommonController, createCommonRoute } from '@ferracinitec/basic-mongodb-crud'

Example

This example provides a URL <your site>/mobile with the HTTP verbs GET (all records using / or /[id] for a specific one), POST, PUT, DELETE, COPY, and PATCH.

import express from 'express'
import basicMongodbCrud from '@ferracinitec/basic-mongodb-crud'
import { MongoClient } from "mongodb"

// Create a public router
const publicRouter = express.Router()

// Connect to MongoDB
const params = new URLSearchParams()

params.append("retryWrites", "true")
params.append("w", "majority")

const { DBHOST, DBPORT, DATABASE, COLLECTION } = process.env
const uri = `mongodb://${DBHOST}:${DBPORT}/?${params.toString()}`
const dbClient = new MongoClient(uri)
const mobile: Collection<Document> = dbClient.db(DATABASE).collection(COLLECTION)

// Create a controller and define a route for GET, POST, PUT, DELETE.
const mobileController = basicMongodbCrud.create(publicRouter, '/mobile', mobile)

or

import express from 'express'
import { CreateCommonController, createCommonRoute } from '@ferracinitec/basic-mongodb-crud'
import { MongoClient } from "mongodb"

// Create a public router
const publicRouter = express.Router()

// Connect to MongoDB
const params = new URLSearchParams()

params.append("retryWrites", "true")
params.append("w", "majority")

const { DBHOST, DBPORT, DATABASE, COLLECTION } = process.env
const uri = `mongodb://${DBHOST}:${DBPORT}/?${params.toString()}`
const dbClient = new MongoClient(uri)
const mobile: Collection<Document> = dbClient.db(DATABASE).collection(COLLECTION)

// Create a controller
const mobileController = new CreateCommonController(mobile)

// Define a route for GET, POST, PUT, DELETE
createCommonRoute(publicRouter, '/mobile', mobileController)

Custom Controller

To create a custom controller, you should extend the CreateCommonController class and override the following methods:

  • verbGetMiddleware: Executed after the find in verbGet, receiving an array with mongodb models. The data can be modified and must be returned.
  • verbGetByIdMiddleware: Same as the verbGetMiddleware, but executed in verbGetById and receives and returns a single model.
  • preUpdateMiddleware: Before the update in verbPut. Receives the ID and the parameters. Must return the parameters to update.
  • postUpdateMiddleware: After the update in verbPut. Receives the updated model to execute other actions. Must return a model.
  • postInsertMiddleware: After the insert in verbPost. Receives the new model to execute other actions. Must return a model.
  • verbGet: Returns an array with the documents searched according to the provided filter.
  • verbGetById: Returns a single model, according to the ID given in the URL.
  • verbPost: Inserts a new model, according to the parameters in the body.
  • verbPut: Updates a model found according to the ID given in the URL with data in the body.
  • verbDelete: Deletes a model found according to the ID given in the URL.
  • verbCopy: Does nothing. Needs implementation.
  • verbPatch: Does nothing. Needs implementation.

Documentation

HTTP Verb GET

A filter can be executed by passing any field of the document in a URL.

const token = 'a Bearer token'
const headers: Headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)

const config = {
	method: 'get',
	mode: 'cors',
	headers: headers,
	redirect: 'follow'
}

const params = new URLSearchParams()
params.append('manufacturer', 'motorola')

const url = `http://localhost/mobile?${params.toString()}`
fetch(url, config)
.then(response => response.json())
.then(data => {
	...
})
.catch(error => console.log('[getDevices]', error))

Regular expressions can be used like this:

const token = 'a Bearer token'
const headers: Headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)

const config = {
	method: 'get',
	mode: 'cors',
	headers: headers,
	redirect: 'follow'
}

const params = new URLSearchParams()
params.append('manufacturer__regex', '[Mm]otorola')

const url = `http://localhost/mobile?${params.toString()}`
fetch(url, config)
.then(response => response.json())
.then(data => {
	...
})
.catch(error => console.log('[getDevices]', error))

Also JSON-specific commands:

const token = 'a Bearer token'
const headers: Headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)

const config = {
	method: 'get',
	mode: 'cors',
	headers: headers,
	redirect: 'follow'
}

const params = new URLSearchParams()
params.append('manufacturer__json', JSON.stringify({
	"$in": [
		"motorola",
		"apple"
	]
}))

const url = `http://localhost/mobile?${params.toString()}`
fetch(url, config)
.then(response => response.json())
.then(data => {
	...
})
.catch(error => console.log('[getDevices]', error))

Also use

  • __fields to determine a list of fields to display;
  • __sort for sorting results
  • __limit to limit the number of results.

To retrieve a specific document

Pass the document ID in the URL.

const token = 'a Bearer token'
const headers: Headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)

const config = {
	method: 'get',
	mode: 'cors',
	headers: headers,
	redirect: 'follow'
}

const url = `http://localhost/mobile/${device._id}`
fetch(url, config)
.then(response => response.json())
.then(data => {
	...
})
.catch(error => console.log('[getDevices]', error))

HTTP Verb POST

To create a new document, perform a POST request to the URL and pass the document in the request body.

const url = 'http://localhost/mobile'
const token = 'a Bearer token'

const headers: Headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)
headers.append('Content-Type', 'application/json')

const config = {
	method: 'post',
	mode: 'cors',
	headers: headers,
	redirect: 'follow',
	body: JSON.stringify({
		manufacture: 'motorola',
		model: 'Moto Gx',
	})
}

fetch(url, config)
.then(response => response.json())
.then(data => setDevice(data))
.catch(error => console.log('[saveDeviceInfo]', error))

HTTP Verb PUT

To update a document, perform a PUT request to the URL, passing the document ID in URL and the fields to be updated in the request body.

const id = device._id
const url = `http://localhost/mobile/${id}`
const token = 'a Bearer token'

const headers: Headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)
headers.append('Content-Type', 'application/json')

const config = {
	method: 'put',
	mode: 'cors',
	headers: headers,
	redirect: 'follow',
	body: JSON.stringify({
		model: 'Moto Gxyz',
	})
}

fetch(url, config)
.then(response => response.json())
.then(data => setDevice(data))
.catch(error => console.log('[saveDeviceInfo]', error))

HTTP Verb DELETE

To delete a document, perform a DELETE request to the URL passing the document ID in the URL.

const id = device._id
const url = `http://localhost/mobile/${id}`
const token = 'a Bearer token'

const headers: Headers = new Headers()
headers.append('Authorization', `Bearer ${token}`)
headers.append('Content-Type', 'application/json')

const config = {
	method: 'delete',
	mode: 'cors',
	headers: headers,
	redirect: 'follow',
}

fetch(url, config)
.then(response => response.json())
.then(data => setDevice(data))
.catch(error => console.log('[saveDeviceInfo]', error))