Mapping Wildcard Paths - Express Endpoints

Learn how to map wildcard paths to system paths for Svelte like endpoints in Express.

This is a continuation of a series on how to build a routing system like Svelte with Express JS.

Previous Tutorials

The previous tutorial gives you a function that is able to pull all of the file paths from a directory and put them into an array. In this tutorial, we will map the file routes to endpoints that we can call and return with express.

The End Goal

The end goal is to take paths from the file system like below and extract any variables and return the full URL and variables in an object. The variables will be defined by putting the variable name inside of square brackets and the endpoint function will be a file in the last folder named +server.js.

1[
2  "./src/accounts/create",
3  "./src/accounts/delete",
4  "./src/assets/[collection][name]",
5  "./src/templates/[name]"
6]

Code

Here is the function I used to take the file paths and collapse them into paths that can be matched by our routing function in the next tutorial. I've added comments explaining how it works line by line.

 1// paths are the file paths from the getFiles() function in the last tutorial
 2function collapsePaths(paths) {
 3  // We will store the Objects that contain the URL and Params here
 4  let collapsed = [];
 5  // Loop through the paths
 6  for (let i = 0; i < paths.length; i++) {
 7    const path = paths[I];
 8    // Use RegExp to get all the [variables] from the path
 9    // vals will only contain the variable names not the square brackets
10    let vals = path.match(/([^[]+(?=]))/g);
11    // If you have the directories setup correctly each path should end in
12    // "+server.js" here we will remove that
13    let ast = path.replace("+server.js", "").slice(5);
14    // Here's where we check if the path has varibles
15    if (vals) {
16      // If it does we need to replace them with the wildcard indicator "*"
17      for (let i = 0; i < vals.length; i++) {
18        ast = ast.replace(`[${vals[i]}]`, "*");
19      }
20    }
21    // Add the processed path to the array
22    collapsed.push({
23      url: ast,
24      params: vals,
25    });
26  }
27  return collapsed;
28}

This function will only be run once to get the location and variables of the endpoints on the server for further processing. In the next tutorial, we will take the collapsed paths and feed them into a function the will match them to any incoming request to our server.