espresso icon indicating copy to clipboard operation
espresso copied to clipboard

Updated to new Deno http server, added static file router, fixed router params, added template engines

Open TKDKid1000 opened this issue 1 year ago • 1 comments

I updated the entire library to use the modern Deno http server version 0.147.0. This did involve changing the project to the fetch Request and Response under the hood, this didn't change the usage at all.

I also added a static file router, you use it via app.static("/public", "./publicdirectory"), then all files under ./publicdirectory are accessible through their url (ie. to access ./publicdirectory/style.css you go to http://localhost:8000/public/style.css)

The other change was fixing your router params system, they weren't working as expected for me (path matching worked, route parameters didn't). I switched it over to Path-to-RegExp for simpler and more familiar usage.

In the second commit, I added template engine support. It is very similar in user syntax to express, usage is as follows:

app.engine("html", htmlEngine);
app.set("views", "./views");
app.set("view engine", "html");

app.get("/engine", async (c) => {
  await c.render("test.html", {
    title: "espresso",
    content: "Welcome to espresso! Rendered with html engine.",
  });
});

Template engines should follow this interface, an example is included:

export type TemplateEngine = (
  filePath: string,
  options: Record<string, unknown>,
) => Promise<string>;

const htmlEngine: TemplateEngine = (path, options) => {
  return new Promise((res, rej) => {
    (async () => {
      try {
        let file = await Deno.readTextFile(path);
        for (const [key, value] of Object.entries(options)) {
          file = file.replaceAll(`{${key}}`, value as string);
        }
        res(file);
      } catch (err) {
        rej(err);
      }
    })();
  });
};

The other minor changes I made were:

  • The body of the context response can now be directly edited
  • The Context#json function now adds the content-type: application/json header automatically
  • Added Context#file function that sends a file to the client
  • Small QOL change: I made the "Server now listening" message send once the server is actually listening.
  • Second commit: fixed method based routing

TKDKid1000 avatar Jul 08 '22 09:07 TKDKid1000