Skip to content

Support custom encoders and decoders #71

@evlist

Description

@evlist

I am using this wonderful tiny library to generate keys for puchdb as suggested in a number of places on the web and I have been confronted to the common issue of supporting integers (#6).

I had also been pondering using dates (ISO formatted) in keys and had the same kind of issue with the additional disadvantage that these dates look ugly when processed by docuri:

image

Think more about this these issues and looking at the code I have noticed that everything would be much easier if there was a way to specify which functions should be used in place of decodeURIComponent and encodeURIComponent and I'd like to propose to add an optional parameter to specify, for each key, which functions should be used (the default being, of course, to use decodeURIComponent and encodeURIComponent.

With this simple modification, it would be possible to define routes such as:

  var page = docuri.route('page/:id', {
    id: { encoder: (v) => v.toString().padStart(5, '0'), decoder: parseInt },
  });

Or, with a helper function:

  const integerType = (n) => {
    return {
      encoder: (v) => v.toString().padStart(n, '0'),
      decoder: parseInt,
    };
  };

  var page = docuri.route('page/:id', {
    id: integerType(3),
  });

Similarly, for dates:

  const dateType = {
    encoder: (v) => v.toISOString(),
    decoder: (v) => new Date(v),
  };

  var page = docuri.route('page/:id', {
    id: dateType,
  });

Let me know what you think and if you want me to submit a PR for this update.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions