1.0.0 • Published 11 days ago

@drftgyhuji7npm/at-omnis-reiciendis v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
11 days ago

Query Strings Parser
=========================
License NPM Version NPM Downloads Travis Coverage Dependencies DependenciesDev Vulnerabilities Releases Contributors Issues

Middleware to transform query strings in a format that is recognized by the MongoDB, MySQL¹ and other databases.

Prerequisites

To ensure the smooth operation of the middleware, your web application must be built using the express.js or hapi.js frameworks.

Installing

Use the npm command to install this library into your project:

npm i @drftgyhuji7npm/at-omnis-reiciendis --save  

Usage Examples

const express = require('express')  
const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')  
const app = express()  
  
app.use(qs()) // middleware @drftgyhuji7npm/at-omnis-reiciendis  
  
app.listen(3000, (req, res) => {  
    console.log('app listening on port 3000')  
})  
  
app.get('/', (req, res) => {  
    res.send('the query is:' + JSON.stringify(req.query))  
})  
  
/**  
 * Request: http://localhost:3000?fields=name,age&skip=10&limit=10&sort=created_at  
 * Result (req.query):  
 * {  
 *    fields: { name: 1, age: 1 },  
 *    sort: { created_at: 1 }  
 *    filters: {},  
 *    pagination: {  
 *        skip: 10,  
 *        limit: 10  
 *    },  
 *    original: '?fields=name,age&skip=10&limit=10&sort=created_at'  
 * }  
 */  

Using custom configurations:

const express = require('express')  
const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')  
const app = express()  
  
app.use(qs({  
  use_page: true,  
  client_db: 'mongodb',  
  date_field: {  
      start_at: 'timestamp',  
      end_at: 'timestamp'  
  },  
  default: {  
      fields: {name: 1 , age: 1, number: 1, _id: 0},  
      sort: { created_at: -1 },  
      filters: {},  
      pagination: {  
          page: 1,  
          limit: 100  
      }  
  }  
}))  
  
/**  
 * Request: http://localhost:3000?fields=name,age&age=30  
 * Result (req.query):  
 * {  
 *    fields: { name: 1, age: 1},  
 *    sort: { created_at: -1 }  
 *    filters: {age: 30},  
 *    pagination: {  
 *        limit: 100,  
 *        page: 1  
 *    },  
 *    original: '?fields=name,age&age=30'  
 * }  
 */  

The middleware uses the following defaults:

options = {  
    use_page: false,  
    client_db: 'mongodb',  
    date_field: {  
      start_at: 'created_at',  
      end_at: 'created_at'  
    },
    default: {  
        fields: {},  
        sort: {},  
        filters: {},  
        pagination: {  
            limit: Number.MAX_SAFE_INTEGER,  
            skip: 0,  
            page: 1  
        }          
    }      
}  

If the options are not provided, the default values will be used for the treatment of queries strings.

For more details, access the wiki page.

Parsers Functions

To use these functions, simply call them through the middleware instance and pass them the query string to be converted and its default values. If you pass the default values ​​a merge will be performed with the result of the query strings. Here are some examples of each analyzer:

  • parser()
const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')

const query = '?fields=name,age&page=1&limit=10&sort=created_at'
console.log(qs.parseFields(query, {}, { use_page: true }))

/**
* Result: 
* {
*   fields: { name: 1, age: 1 },
*   sort: { created_at: 1 },
*   filters: {},
*   pagination: { limit: 10, page: 1 },
*   original:  '?fields=name,age&page=1&limit=10&sort=created_at'
* }
*/

For more details >>

  • parseFields()
const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')

const query = '?fields=name,age'
console.log(qs.parseFields(query))

/**
* Result: 
* { 
*     name: 1,
*     age: 1
* }
*/

For more details >>

  • parseSort()
const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')

const query = '?sort=name,-age,created_at'
console.log(qs.parseSort(query))

/**
* Result: 
* { 
*     name: 1,
*     age: -1,
*     created_at: 1
* }
*/

For more details >>

  • parsePagination()
const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')

const query = '?limit=20&page=3'
console.log(qs.parsePagination(query, {}, true))

/**
* Result: 
* { 
*     limit: 20,
*     page: 3 
* }
*/

For more details >>

  • parseFilter()
 const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')
 
 const query = '?name=elvis&age=80'
 console.log(qs.parseFilter(query))
 
 /**
 * Result: 
 * { 
 *     name: 'elvis',
 *     age: 80
 * }
 */

For more details >>

  • parseDate()

    const qs = require('@drftgyhuji7npm/at-omnis-reiciendis')
    
    const query = '?start_at=2019-02-05T00:00:00&end_at=2019-02-05T23:59:59'
    console.log(qs.parseDate(query))
    
    /**
  • Result:
  • {
  • $and: [
  •   { created_at: { lt: 2019-02-05T23:59:59 }},
  •   { created_at: { gte: 2019-02-05T00:00:00 }}
  • ]}
  • } */
    For more [details >>](https://github.com/drftgyhuji7npm/at-omnis-reiciendis/wiki/4.-Parsers#parsedate)

Supported Query Strings

For informations and details about the supported query strings, access the wiki page.


Future Features

  • ¹Support for relational databases such as MySQL, PostgreSQL and SQLite.
toStringTagtoSortedES2021jestmake dirobjectReactiveXschemaxhrdatacolumninputnopegradients css3dropString.prototype.matchAllobjfindLastrgbJSONchinesesymbolsettingsECMAScript 2020threeisConcatSpreadableredux-toolkitieeast-asian-widthzoditerateless mixinsargparsewritablestructuredClonejapanesegraphqlwarningtypedarrayWeakSettyped arrayiterationes2015launchestreeYAMLschemewindowsminimaltapesetImmediatees-abstractES2018callboundnodejsslicereduceclass-validatorunicodequeryfseventsconsume-0whatwgsharedarraybufferStream6to5matchesfast-copyjsyupcallflatmomentassertionECMAScript 2022MicrosoftmapstringifypathworkerbusyslotopenforEachhookssuperstructchromiumttyregexpefficientECMAScript 6whichstyleguidedataViewoptimistinstallermobilenamescss nestinghttprandommoveauthtypedvalidatorkeyRxJStelephoneidleuser-streamscss variablenamepipeurlsjQueryserializationArray.prototype.flatMappolyfillmonorepoFunction.prototype.nameimmeruuidcreatetrimpackageslanguageartcallbindexpressionjasminenested cssredactUint8ClampedArraycurlmulti-packagelazywalkingassertswaapidescriptionformatwebpersistentairbnbenvbootstrap lessserializerArray.prototype.flatRegExp#flagsutilitiesmochaphoneWebSocketsweakmapcachevalueBigInt64ArraycoerciblemetadatautilpropertiessomeArrayBuffer#sliceargsURLprototouchpopmotionfputil.inspectwgetharmonyhandlerstrimLeftEScharactersbrowserprotocol-buffersjsxfunctional.envcensorjson-schemaqueueMicrotaskxsswatcherECMAScript 2017optionhaspostcss-plugindayjsmime-dbInt16Arrayreact-hook-formvestanimationarraysECMAScript 2018taskutilityserializelinuxargumentswebsiteES2023ES2020appsortawesomesauceparentstextjavascriptencryptioncall-boundlesscsspromisewatchingnegativeextrarm -rfarrayratepreserve-symlinksURLSearchParamsshrinkwrapcharacterflatMapsafeponyfillUint32ArrayextensionfinduptimeTypeBoxArray.prototype.includestslibmiddlewareparserObject.entrieslook-uprecursivefoldermergecolors_.extendsameValueZeroeslint-plugintranspilerstartsequencelengthReflect.getPrototypeOf0Array.prototype.flattennodetacitregular expressionsmakebuffertses-shim APIspawninternal slotreact animationhttpseslintplugincsslintsymbolsRFC-6455assertstatusquotegetmruidES2019wordbreakdateprogresssyntaxerrorSymbol.toStringTagjoidependenciessymlinksscheme-validationflagisdeepzeroformattingconnectvalidclientworkspace:*lessinferenceenumerableduplexoutputflagscss lessECMAScript 2016ObservablesstreamsignalInt8ArrayAsyncIteratorshebangArrayBuffer.prototype.slicees2017readablestreambundlingsigintplugincallbackpureprunebyteObjectincludesgetoptvarramdaawaitpoint-freematchAlldeleteconfigurablepatchbannerregexUint16Arrayglobform-validationmacosmimetypesguidhardlinkstrimStartdependency managerviewspinnersextendposeshimcolourtypescriptdragsuperagentcomputed-typesspeedperformancefind-upcall-bindnpmECMAScript 2015core-jscheckgrouptypedarraysCSSintrinsicnegative zeroxdg-openyamlchaiconstiteratorstringvariablesurlratelimitpnpm9ansipushObject.keysasyncjson-schema-validatorspeclogginggroupBysetPrototypeOfmodulesdeep-copybyteOffsethashSymbolArray.prototype.findLastIndexECMAScript 5es8syntaxexecutableES3matchfastqueuefantasy-landchildcmdauthenticationeditorcompile lesslastformsconcatMappropertyArray.prototype.findLastUnderscoreObject.getPrototypeOfelectronpostcssstyled-componentsconcatuninstallfast-deep-copyerrorwalkcurried@@toStringTagdom-testing-libraryeslintcollection.es6clonedefaultexpressterminalinvariantchannela11yirqlinkrmFloat64ArrayESnextstartermimevalidationautoprefixerbcryptECMAScript 2023ES2016variables in csssigtermfunctionsearchwatchrangeerrorpackage.jsongenericsnativedefinePropertyfastclonenumberrmdirconsolestylingperformantboundStyleSheetxdgbabelreact-testing-libraryTypeScriptio-tsshamFloat32ArrayObject.fromEntriesPromiseemitassignvalidatemkdirsfilterfindLastIndexes2016json-schema-validationtakecryptosetReactiveExtensionspreprocessorlockfileArray.prototype.filterbabel-corecoretddjsonschemacjkES8PushinterruptsajvJSON-Schemafast-cloneprocessgradients css$.extendcolortypeerrormodulewrapcliECMAScript 2021toobjectsignalstostringtagsanitizefile systemECMAScript 3resolve[[Prototype]]mkdironceprefixspinnerenderinternaldatastructurestringifierclasseschromelimitedSetcontainsstreamsjsdomgetintrinsicdescriptorkeysstatelesssharedoffsetless cssomitObservablepositivebatchjsdiffStreamsdataviewdescriptorsECMAScript 7optimizercollectionaccessibilitycss-in-jsdirdebuggerlimitIteratorexec3dcompareconfigtypesdefinestylesheetl10nruntimepackage managerjsonpathlinewrapgetteres5
1.0.0

11 days ago