Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom encoders and decoders #71

Open
evlist opened this issue Nov 9, 2022 · 0 comments
Open

Support custom encoders and decoders #71

evlist opened this issue Nov 9, 2022 · 0 comments

Comments

@evlist
Copy link

evlist commented Nov 9, 2022

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!

@evlist evlist changed the title Support custom encoders and décoders Support custom encoders and decoders Nov 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant