@imjano/get_query_from_url_mw
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

Get query from URL

The function extracts construct a URL object from the request parameters. It then creates a query object based on the URL query string, which will be used for querying a database using mongoose. The constructed query object is then inserted into the req parameter for further processing in subsequent middleware or route handlers.

Installation

npm install @imjano/get_query_from_url_mw

Usage

import the middleware @imjano/get_query_from_url_mw

const GetQueryFromURLMiddleware = require('@imjano/get_query_from_url_mw')

Now you can configure according to your project and insert it before your routes

const getQueryFromURL = GetQueryFromURLMiddleware.configure({
	defaultFields: {
		id: '_id',
		timestampCreatedAt: 'createdAt',
		timestampUpdatedAt: 'updatedAt',
	},
})
app.use(getQueryFromURL)

let's suppose that the path of the request ends as follows

'example?from=2023-05-10'&param=name&equalTo=alex

req.queryFromURL has been injected with query objects

{
	query: { createdAt: { '$gte': '2023-05-10' }, name: 'alex' },
	sort: { createdAt: -1 },
	limit: 100
}

Now you can execute the query

app.get('/example', async (req, res, next) => {
	const { query, sort, limit } = req.queryFromURL
	let users = await UserModel.find(query).sort(sort).limit(limit)
	res.json(users).status(200)
})

Package Sidebar

Install

npm i @imjano/get_query_from_url_mw

Weekly Downloads

0

Version

1.0.0

License

ISC

Unpacked Size

25.8 kB

Total Files

20

Last publish

Collaborators

  • imjano