Session

Session mannager in Vixeny.

Examples

Basic Example

Cheking for a valid session

Session are validated at the resolution of the CTX

import { components, wrap } from "vixeny";

const user = components.session<{ hello: string }>({
  removeDeleteUnsedSession: true,
});

const handler = wrap({
  // Adding the plugin
  cyclePlugin: {
    user,
  },
})()
  .stdPetition({
    path: "/",
    f: ({ user }) => {
      // Returns the current session
      return user.newSession({ hello: "hi" });
    },
  })
  .stdPetition({
    path: "/only",
    // Returns a true if the user has a valid session
    f: ({ user }) => String(user.valid),
  })
  .testRequests();

const req = new Request("http://localhost/");

// Gets session
const token = await handler(req)
  .then((res) => res.text());

// Adding the session to a cookie
const isSession = new Request("http://localhost/only", {
  headers: {
    Cookie: "session=" + token,
  },
});

// Sending a request without a session
await handler(new Request("http://localhost/only"))
  .then( res => res.text())
  // Logs `false`
  .then(console.log)

// Sending a request with a valid session
await handler(isSession)
  .then( res => res.text())
  // Logs `true`
  .then(console.log)