Coder Social home page Coder Social logo

url-template's Introduction

A JavaScript URI template implementation

This is a simple URI template implementation following the RFC 6570 URI Template specification. The implementation supports all levels defined in the specification and is extensively tested.

Installation

For use with Node.js or build tools you can install it through npm:

$ npm install url-template

If you want to use it directly in a browser use a CDN like Skypack.

Example

import { parseTemplate } from 'url-template';

const emailUrlTemplate = parseTemplate('/{email}/{folder}/{id}');
const emailUrl = emailUrlTemplate.expand({
  email: 'user@domain',
  folder: 'test',
  id: 42
});

console.log(emailUrl);
// Returns '/user@domain/test/42'

A note on error handling and reporting

The RFC states that errors in the templates could optionally be handled and reported to the user. This implementation takes a slightly different approach in that it tries to do a best effort template expansion and leaves erroneous expressions in the returned URI instead of throwing errors. So for example, the incorrect expression {unclosed will return {unclosed as output. The leaves incorrect URLs to be handled by your URL library of choice.

Supported Node.js versions

The same versions that are actively supported by Node.js are also supported by url-template, older versions of Node.js might be compatible as well, but are not actively tested against.

url-template's People

Contributors

bouzuya avatar bramstein avatar dependabot[bot] avatar elmerbulthuis avatar fdawgs avatar gr2m avatar jonkoops avatar knownasilya avatar lencioni avatar oblador avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

url-template's Issues

Switch for already encoded data

Is there a way for the template to not call encodeURIComponent, for if the data is already in the proper encoding when passed to '''expand''' ?

Incorrect Types for expand.

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Type was incorrect for Template.expand as it did not allow objects that contain arrays. Resolved by changing the type as below.

Here is the diff that solved my problem:

diff --git a/node_modules/url-template/lib/url-template.d.ts b/node_modules/url-template/lib/url-template.d.ts
index feae94a..8a9b227 100644
--- a/node_modules/url-template/lib/url-template.d.ts
+++ b/node_modules/url-template/lib/url-template.d.ts
@@ -1,7 +1,7 @@
 export type PrimitiveValue = string | number | boolean | null;
 
 export interface Template {
-  expand(context: Record<string, PrimitiveValue | PrimitiveValue[] | Record<string, PrimitiveValue>>): string;
+  expand(context: Record<string, PrimitiveValue | PrimitiveValue[] | Record<string, PrimitiveValue | PrimitiveValue[]>>): string;
 }
 
 export function parseTemplate(template: string): Template;

This issue body was partially generated by patch-package.

TypeScript usage

Unclear how to import this module with typescript.

Dependencies added:

yarn add url-template
yarn add @types/url-template --dev

tried:

import urltemplate from "url-template";
import { urltemplate } from "url-template";
import { TemplateParser } from "url-template";
import { Template } from "url-template";

all say no such export.

Expand nested objects

Is it possible to do something like this?

const params = {
    user: {
        id: 123
    }
};

template.parse("/users/{user.id}").expand(params); // => "/users/123"

"that.encodeReserved is not a function" when parse() is called

TypeError: that.encodeReserved is not a function
at /opt/PROJECT/node_modules/url-template/lib/url-template.js:171:25
at String.replace (native)

summary of code in main file of express app

t = urlTempl.parse(href); // works fine , called in main file

// called inside a route;
url = t.expand( { email: req.params.email } ); // above error

I try to replicate this issue in my tests .. but I must be missing something obvious
because url-temple always manage to work there ...

Change API

Change API so that:

var template = require('url-template');

var myUrl = template.parse('/{some}/{url}');

myUrl.expand(...);

works, instead of having to instantiate the UrlTemplate class.

Parse should parse

At present parse returns an object with a an expand method in it. Parse does not do any ahead of time work, all of the work of parsing the template &c is part of the second expand method.

Ideally, parse would do some parsing work, such that the expand method could be shorter & do less work. If I am trying to make 1000 requests/second to a service, I don't want to have to keep re-parsing the template for each of these requests: I'd expect the parse method to break up & parse the template, such that the expand method could simply drop values into place & go.

no license

could you please give it any license ?

A code is implicitly copyrighted the moment it is written, and, by default, you have no legal right to redistribute it, or produce derived works from it (of course, the author might not mind, but that's another matter entirely). In other words, lack of license is roughly the same as "look but don't touch" license."

option to leave unknown params

Would it be acceptable to add an option to the expand function which would allow parameters to be expanded only if they are known/set? For example

var template = urlTemplate.parse('/cars/{model}/engine/{engineId}');
console.log(urlTemplate.expand({model: "ford-taurus"}, false);
// "/cars/ford-taurus/engine/{engineId}"

see my fork for the hack i'm currently using

My use case is for dynamic generation of hypermedia links for subresources where certain parameters are known, but other still need to be filled in

Transpile to CommonJS

I'm just wondering, is there a reason you're not transpiling a CommonJS version of the package and offering both CJS and ESM? It's making it very difficult, nay, impossible to create downstream "dual packages". ๐Ÿ˜ข

Please add license to package.json

Please could you add the BSD license to package.json? This will ensure that any automated tools that check the license on NPM will be able to determine it's BSD-based. Thank you.

Is this package dead?

@bramstein it looks like there are several issues and PRs open since quite some time. Do you need help maintaining this package or are you willing to perhaps add me as a maintainer? I'm working on a project that uses this library and I would like to help modernize this package so we can keep using it.

Let met know.

Missing arrays and objects in type definition

Expanding objects and array variables is supported.

But the type definition of expand does not reflect this.

It should probably be more like:

type VariableValue = string | number | boolean | null | VariablesMap;
type VariablesMap = Record<string, VariableValue>;

export interface Template {
  expand(context: VariablesMap): string;
}

Importing package inside a Jest test is problematic (ESM export not CJS)

Currently the main export is using:

export function parseTemplate(template) {

which is tricky when using this library inside a Jest test suite. Jest do only handle CommonJS modules fine right now and this construction lead to a parse error. It might be possible to work-around the issue by having a quite complex extension in the configuration to compile this node_module, but easier would be without.

Error message from Jest:

Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

...

Details:

    MY_PROJECT/node_modules/url-template/lib/url-template.js:97
    export function parseTemplate(template) {
    ^^^^^^

When changing the line to:

exports.parseTemplate = function parseTemplate(template) {

everything works fine.

Should have an option to force an error for missing required template variables

Currently if there is a URL template that contains a required template variable:

.../?required={required}{&page,page_size}

the expand function will not throw an error if the context does not include this required value.

I would like an option to set a 'strict' mode upon instantiation:

new UrlTemplate(this.href, true); // Second argument sets the mode to strict

I believe this can be done in a backwards compatible way.

Should the expand function allow for undefined?

I'm using this module on a variable that will be a string but sometimes due to bad data, the string could be undefined. The module currently throws the following error when trying to expand a variable that was parsed with undefined Cannot read property 'replace' of undefined.

Instead of doing urlTemplate.parse(item.url || '') every time the module is used, it would be good if there was a default value of an empty string so no errors are thrown.

Here's the error reproduced:
https://runkit.com/59106f7a0c1a3d00124401b6/591077f93ae0c30012649458

3.0.0 migration guide suggests cjs syntax is usable but we get errors when we use require. Please clarify if CJS is supported

Hi,

The 3.0.0 migration guide suggests I can use the following syntax to use version 3.0.0:

const { parseTemplate } = require('url-template');
const emailUrlTemplate = parseTemplate('/{email}/{folder}/{id}');

But when I do so in my project I get the following error message:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /root/*********/browzine_cms/node_modules/url-template/lib/url-template.js
require() of ES modules is not supported.
require() of /root/*********/browzine_cms/node_modules/url-template/lib/url-template.js from /root/*********/browzine_cms/lib/models/user_model.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename url-template.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /root/*********/browzine_cms/node_modules/url-template/package.json.

Can you advise if CJS style imports are actually still intended to be supported? Do I need to do something on my end or is this an issue in url-template that the syntax in the migration guide isn't working?

v2.0.4 does not include LICENSE

Please release a version that includes your LICENSE file so that I can parse and included for the credits section of my app.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.