Skip to content

$session

import { $session } from "dreamkit";

Define sessions with parameters and use them as required or optional in api and middleware.

If you want to get/set the session params directly you can use SessionHandler.


Definition

const $session: {
name(value: string): typeof $session;
params(value: object): typeof $session;
timelife(value: { minutes?: number; days?: number }): typeof $session;
create(): {
new (params: object): {
params: object;
};
};
};

name

You can have as many sessions as you want, since each one of them will use the name option that you have assigned.

params

Sets the session parameter scheme. If the client session parameters do not match the scheme the session will be considered null.

timelife

Delete the session when it exceeds the maximum lifetime.

If no lifetime is specified it will never be deleted.

create

Creates a strongly typed and validated class which allows receiving the configured parameters as the first argument.

class UserSession extends $session
.name("user")
.params({
id: s.string(),
})
.create() {}
const session = new UserSession({ id: 1 });
console.log(session.params.name); // 1

Examples

Auth

import {
$api,
$route,
$session,
createAction,
Input,
iocParam,
s,
SessionHandler,
} from "dreamkit";
import { createEffect, createResource, createSignal, Show } from "solid-js";
class UserSession extends $session
.name("user")
.params({ id: s.number() })
.create() {}
const login = $api
.title("Login")
.params({
name: s.title("Name").string(),
password: s.title("Password").string(),
})
.self({ SessionHandler })
.create(async function (params) {
if (params.name === "admin" && params.password === "admin") {
await this.sessionHandler.set(UserSession, { id: 1 });
} else {
throw new Error("Invalid auth");
}
});
const logout = $api
.title("Logout")
.self({ SessionHandler })
.create(async function () {
await this.sessionHandler.unset(UserSession);
});
const fetchSessionData = $api
.title("Try fetch session params")
.self({ UserSession })
.create(async function () {
return { id: this.userSession.params.id };
});
const checkAuth = $api
.title("Check auth")
.self({ UserSession: iocParam(UserSession).optional() })
.create(function () {
return !!this.userSession;
});
export default $route
.api({ login, logout, fetchSessionData, checkAuth })
.params({ name: login.params.name.optional() })
.path("/")
.create(({ api, params }) => {
const [name, setName] = createSignal(params.name ?? "");
const [password, setPassword] = createSignal("");
const logout = createAction(api.logout);
const fetchSessionData = createAction(api.fetchSessionData);
const [checkAuth, { refetch }] = createResource(api.checkAuth);
const login = createAction(api.login).with(() => ({
name: name(),
password: password(),
}));
createEffect(() => logout.state && refetch());
createEffect(() => {
if (login.state === "success") {
refetch();
setName("");
setPassword("");
}
});
return (
<>
<p>checkAuth: {checkAuth.latest ? "true" : "false"}</p>
<p>
<button
onClick={fetchSessionData}
disabled={fetchSessionData.running}
children={fetchSessionData.title}
/>{" "}
{fetchSessionData.error
? fetchSessionData.error.message
: fetchSessionData.result
? JSON.stringify(fetchSessionData.result)
: undefined}
</p>
<Show when={checkAuth.latest === true}>
<button
onClick={logout}
disabled={logout.running}
children={logout.title}
/>
</Show>
<Show when={checkAuth.latest === false}>
<Input
placeholder={login.params.name.options.title}
value={name}
onChange={setName}
/>
<Input
type="password"
placeholder={login.params.password.options.title}
value={password}
onChange={setPassword}
/>
<button
type="submit"
onClick={login}
disabled={login.running}
children={login.title}
/>
{login.error?.message}
</Show>
</>
);
});

Temporary session

import {
$api,
$route,
$session,
createAction,
iocParam,
s,
SessionHandler,
} from "dreamkit";
import { createEffect, createSignal, onCleanup } from "solid-js";
class TempSession extends $session
.name("temp")
.params({ date: s.number() })
.timelife({ seconds: 5 })
.create() {}
const create = $api
.title("Create")
.self({ SessionHandler })
.create(async function () {
await this.sessionHandler.set(TempSession, { date: Date.now() });
});
const check = $api
.title("Check")
.self({ TempSession: iocParam(TempSession).optional() })
.create(function () {
return !!this.tempSession;
});
export default $route
.api({ create, check })
.path("/")
.create(({ api }) => {
const [cookies, setCookies] = createSignal("");
const [counter, setCounter] = createSignal<number>();
const create = createAction(api.create);
const check = createAction(api.check);
let interval: any;
const startCounter = () => {
setCounter(5);
check();
clearInterval(interval);
interval = setInterval(() => {
if (counter() === 0) return clearInterval(interval);
setCounter(counter()! - 1);
check();
}, 1000);
};
createEffect(() => {
create.state === "success" && startCounter();
});
createEffect(() => {
check.state === "success" && setCookies(document.cookie);
});
onCleanup(() => clearInterval(interval));
return (
<>
<p>timeleft: {counter()}</p>
<p>cookies: {cookies()}</p>
<button
onClick={create}
disabled={create.running}
children={create.title}
/>
<button
onClick={check}
disabled={check.running}
children={
<>
{check.title}: {JSON.stringify(check.result)}
</>
}
/>
</>
);
});