A middleware function getSession(request, opts): void
retrieves a session
from the database and attaches it to the request
, using specified opts
.
- If the route is not secure, the function will exit early;
- If the route is secure and no
user account
is associated with thesession
, it will redirect to the /home page; - If the route is secure and no
user profile
is linked to thesession
, it will redirect to the /create-profile page.
As a consequence, the request.session
can have one of three states:
- No
user account
, - A
user account
, or - A
user account
and auser profile
.
Question:
How can I determine the type of request.session
based on the input request
and opts
in getSession()
?
Example:
The current types, implementation, and usage details for getSession()
are outlined below.
// utils/types.ts
interface Session {
id: number;
// ...
account: Account | null;
}
interface Account {
id: number;
// ...
profile: Profile | null;
}
interface Profile {
id: number;
// ...
}
interface HttpRequest extends Request {
session: Session;
}
// utils/session.ts
const getSession = async (request: HttpRequest, opts: { protected?: boolean } = {}) => {
// Set request.session to session fetched from database
// EXAMPLE: session with an account and no profile
request.session = { id: 1, account: { id: 1, profile: null } };
// If route is not secure: exit early
if (!opts.protected) {
return;
}
// If route is secure and there is no account: redirect to /home page
if (!request.session.account) {
throw new Response(null, { status: 302, headers: { Location: "/home" } });
}
// If route is secure and there is no profile: redirect to /create-profile page
if (!request.session.account?.profile) {
throw new Response(null, { status: 302, headers: { Location: "/create-profile" } });
}
};
// routes/create-profile.tsx
const loader = async (request: HttpRequest) => {
try {
await getSession(request, { protected: true });
// TODO:
// Determine if the request.session has an account or profile after calling getSession()
// EXAMPLE:
// If route is secure and no redirection to /home page:
// Assume that there is an account, i.e. request.session.account is not null
const account = request.session.account;
return null;
} catch (error) {
return error;
}
};