Fastjs Documentation

website·Indexed 30 days ago

https://docs.fastjs.dev

A lightweight JavaScript utility library (npm: jsfast) providing a tiny fetch wrapper for requests, a dependency-free Date replacement via FastjsDate, DOM manipulation tools via FastjsDom, and a safe wrapper for cookies.

Tokens
13.7K
Snippets
92
Records
101
Agent score
52%

What's inside Fastjs

  1. Overview of the jsfast cookie module

    The cookie module is a safe wrapper around document.cookie that automatically handles encodeURIComponent for names and values. It supports standard cookie attributes like Max-Age, expires, path, domain, secure, and SameSite. It is SSR-safe: if document is missing (e.g., in Node.js), reads return null and writes are silently skipped without throwing errors.
    import { cookie } from "jsfast";
  2. Overview of Fastjs toolkit

    Fastjs (npm: jsfast) is a tiny, zero-dependency JavaScript toolkit that provides a consistent, type-safe API for common front-end tasks. It is designed to be tree-shakeable, has no global side-effects, and works in both browsers and Node.js (version 18 or higher). The library uses a chainable, return-this pattern across its modules and provides full TypeScript declarations without requiring separate @types packages.
  3. Overview of FastjsModuleBase

    FastjsModuleBase is the common internal factory base inherited by all Fastjs instances, including FastjsDom, FastjsDomList, FastjsDate, FastjsRequest, and FastjsCookie. It provides a standardized surface for attaching business data (custom props), defining named methods (custom events), and scheduling callbacks within a chain (then).
  4. Understand the Fastjs Request Hook lifecycle

    Fastjs provides four request-level hooks that execute in a specific order. Hooks can read or mutate requests/responses and can interrupt the pipeline by returning false. They may return a Promise<boolean | undefined> which is awaited by the library.

    Request Phase:

    • before: The instance exists, but the Request object is not yet built. Use this to modify request.config (headers, query, body).
    • init: The Request object exists and is about to be passed to fetch. Changes to request.config here are too late, but you can still abort the request.

    Response Phase:

    • success: The response has been parsed and matches the configured success code (default: 2xx).
    • failed: The response failed (non-2xx) or the underlying fetch threw an error.
  5. Import the jsfast date module

    The date module provides a dependency-free replacement for common Date operations, supporting two-way conversion between format strings and Date objects. It works in both browsers and Node.js.
    import { date } from "jsfast";
  6. Create and configure new DOM elements

    Use dom.newEl(tagName, options) to create a detached DOM element. The options object allows you to set properties, styles, attributes, and content immediately upon creation.
    dom.newEl("div", {
      id: "card", // Writable property
      textContent: "Hello World", // Writable property
      css: {
        color: "red",
        backgroundColor: "black",
      }, // CSS object or raw string "color: red;"
      attr: {
        href: "/home",
        "data-id": "1",
        rel: null, // null removes the attribute
      },
      text: "Hello World", // Shorthand for text content
      html: "<h1>Hello World</h1>", // Shorthand for innerHTML
      val: "Hello World", // Shorthand for value (e.g. for inputs)
      class: "card card--primary", // String or array: ["card", "card--primary"]
    });
  7. Implement request debouncing

    Use config.wait (in milliseconds) to collapse multiple calls into one. The request will only fire after the specified wait time has passed without another call. Calling .abort() while the timer is pending will cancel the request.
    import { dom, request } from "jsfast";
    
    dom.newEl("button", { text: "Click me" }).addEvent("click", () => {
      request
        .get("https://reqres.in/api/users", null, { wait: 1000 })
        .then((data) => console.log(data));
    });
  8. Create a scoped cookie instance

    Use cookie.create(path?, domain?) to create a FastjsCookie instance. This instance pre-fills the specified path and domain for all subsequent set and remove calls. Note that get calls on a scoped instance still read from document.cookie globally.
    import { cookie } from "jsfast";
    
    const adminCookie = cookie.create("/admin", ".example.com");
    
    adminCookie.set("token", "abc"); // automatically uses path=/admin; domain=.example.com
    adminCookie.remove("token"); // automatically uses same scope
    adminCookie.get("token"); // reads globally
  9. Import and initialize the Fastjs dom module

    The dom module provides a type-safe way to operate on DOM elements. It relies on document and window and will throw errors if accessed in non-browser environments. To discriminate between single element wrappers (FastjsDom) and list wrappers (FastjsDomList) at runtime, use type guards like isDom or isDomList.
    import { dom } from "jsfast";
  10. Set a cookie with jsfast

    Use cookie.set(name, value, options) to store a cookie. The method returns the scoped object, allowing for method chaining (e.g., .set().set().remove()).
    import { cookie } from "jsfast";
    
    // Basic set
    cookie.set("name", "value");
    
    // With expiration (1 hour)
    cookie.set("name", "value", { maxAge: 3600 }); // seconds
    cookie.set("name", "value", { expires: 1000 * 60 * 60 }); // ms
    cookie.set("name", "value", { expires: new Date("2030-01-01") });
    
    // With scope and security
    cookie.set("name", "value", {
      path: "/admin",
      domain: ".example.com",
      sameSite: "Lax",
      secure: true,
    });
  11. Replace archived Fastjs CLI with Vite

    The fastjs-team/cli repository was archived on December 22, 2023, and is no longer maintained. It may be incompatible with current versions of jsfast. For new projects, the recommended approach is to scaffold a project using Vite and then install jsfast manually.
    npm create vite@latest my-project
    cd my-project
    npm i jsfast
  12. Create a FastjsDate instance

    Use date.create() to create a FastjsDate instance for advanced date workflows. Note that FastjsDate is a TypeScript type only; you must use the date.create runtime constructor rather than new FastjsDate().
    import { date } from "jsfast";
    import type { FastjsDate } from "jsfast";
    
    const d: FastjsDate = date.create();
    console.log(d.toString());