Skip to content

Make Request method parseQueryString configurable #73

@enixsoft

Description

@enixsoft

Prerequisites

Currently AdonisJS parses query strings in requests by default in @adonisjs/http-server/build/src/Request/index.js method parseQueryString using package qs:

parseQueryString() {
    if (this.parsedUrl.query) {
        this.updateQs(qs_1.default.parse(this.parsedUrl.query));
        this.originalRequestData = { ...this.requestData };
    }
}

But the parse method of qs here is not configurable at all, even though the package offers many options:

interface IParseOptions {
    comma?: boolean | undefined;
    delimiter?: string | RegExp | undefined;
    depth?: number | false | undefined;
    decoder?: ((str: string, defaultDecoder: defaultDecoder, charset: string, type: 'key' | 'value') => any) | undefined;
    arrayLimit?: number | undefined;
    parseArrays?: boolean | undefined;
    allowDots?: boolean | undefined;
    plainObjects?: boolean | undefined;
    allowPrototypes?: boolean | undefined;
    parameterLimit?: number | undefined;
    strictNullHandling?: boolean | undefined;
    ignoreQueryPrefix?: boolean | undefined;
    charset?: 'utf-8' | 'iso-8859-1' | undefined;
    charsetSentinel?: boolean | undefined;
    interpretNumericEntities?: boolean | undefined;
}

Why this feature is required (specific use-cases will be appreciated)?

My use case is to allow comma separated values for array so instead of unnecessary long query strings like:
someArray[]=1&someArray[]=2&someArray[]=3
I can just send
someArray=1,2,3

Have you tried any other work arounds?

My work around is this hack to override parseQueryString method in Request class using macro.
In my AppProvider.ts:

public async boot() {
    const Request = this.app.container.use('Adonis/Core/Request')

    Request.macro('parseQueryString', function () {
      if (this.parsedUrl.query) {
        this.updateQs(qs.parse(this.parsedUrl.query, { comma: true }))
        // @ts-ignore
        this.originalRequestData = { ...this.requestData }
      }
    })
  }

Solution

Add optional "queryString" object of type QueryStringConfig (this is already used in @adonisjs/bodyparser package) to RequestConfig (part of ServerConfig in config/app.ts).
and that could be used in relevant line of parseQueryString method:
this.updateQs(qs_1.default.parse(this.parsedUrl.query, this.config.queryString || {}));

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions