Build Type-Safe URLs With typage-url Library

Category: Javascript | July 24, 2023
Author:
Views Total:19 views
Official Page:Go to website
Last Update:July 24, 2023
License:MIT

Preview:

Build Type-Safe URLs With typage-url Library

Description:

A lightweight TypeScript library that leverages TypeScript to create type-safe URL paths for web applications. It validates route configurations and generates the correct URLs.

How to use it:

1. Install and import the typage-url.

import { 
  createPath, 
  END,
  build,
} from 'typage-url';

2. Creates an URL path object using the createPath method.

const root = createPath({
      CSS: {},
      Script: {
        [END]: true,
        subpage1: {}
      },
      Com: {
        subpage1: {}
      }
});

3. Get the available URLs using the build method.

// '/css'
build(root.css);
// '/script'
build(root.script); 
// '/script/subpage1'
build(root.script.subpage1);
// '/com'
build(root.com); 
// => '/com/subpage1'
build(root.com.subpage1);

4. It also supports URLs with path parameters.

const root = createPath({
      posts: {
        ':id': {}
      }
});
// '/posts/10'
build(root.users.id('10'));

5. Add a prefix to the URLs.

const root = createPath({
      CSS: {},
      Script: {
        [END]: true,
        subpage1: {}
      },
      Com: {
        subpage1: {}
      }
}, '/prefix');
// '/prefix/css'
build(root.css);
// '/prefix/script'
build(root.script); 
// '/prefix/script/subpage1'
build(root.script.subpage1);
// '/prefix/com'
build(root.com); 
// => '/prefix/com/subpage1'
build(root.com.subpage1);

You Might Be Interested In:


Leave a Reply