Skip to content

Commit

Permalink
Update session types
Browse files Browse the repository at this point in the history
  • Loading branch information
timleslie committed Feb 11, 2021
1 parent e8d20e6 commit 4e15413
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
5 changes: 5 additions & 0 deletions .changeset/twenty-dogs-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystone-next/keystone': patch
---

Updated types of session functions.
24 changes: 9 additions & 15 deletions packages-next/keystone/src/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@ function generateSessionId() {
return uid(24);
}

function asSessionStrategy<TSessionStrategy extends SessionStrategy<any>>(
sessionStrategy: TSessionStrategy
): TSessionStrategy {
return sessionStrategy;
}

const TOKEN_NAME = 'keystonejs-session';
const MAX_AGE = 60 * 60 * 8; // 8 hours

Expand Down Expand Up @@ -67,13 +61,14 @@ type FieldSelections = {
[listKey: string]: string;
};

type CreateSession = ReturnType<typeof statelessSessions>;

/* TODO:
- [ ] We could support additional where input to validate item sessions (e.g an isEnabled boolean)
*/

export function withItemData(createSession: CreateSession, fieldSelections: FieldSelections = {}) {
export function withItemData<T extends { listKey: string; itemId: string }>(
createSession: () => SessionStrategy<T>,
fieldSelections: FieldSelections = {}
): () => SessionStrategy<T & { data: any }> {
return (): SessionStrategy<any> => {
const { get, ...sessionStrategy } = createSession();
return {
Expand Down Expand Up @@ -115,23 +110,22 @@ export function withItemData(createSession: CreateSession, fieldSelections: Fiel
};
}

export function statelessSessions({
export function statelessSessions<T>({
secret,
maxAge = MAX_AGE,
path = '/',
secure = process.env.NODE_ENV === 'production',
ironOptions = Iron.defaults,
}: StatelessSessionsOptions): () => SessionStrategy<Record<string, any>> {
}: StatelessSessionsOptions): () => SessionStrategy<T> {
return () => {
if (!secret) {
throw new Error('You must specify a session secret to use sessions');
}
if (secret.length < 32) {
throw new Error('The session secret must be at least 32 characters long');
}
return asSessionStrategy({
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async get({ req, createContext }) {
return {
async get({ req }) {
if (!req.headers.cookie) return;
let cookies = cookie.parse(req.headers.cookie);
if (!cookies[TOKEN_NAME]) return;
Expand Down Expand Up @@ -169,7 +163,7 @@ export function statelessSessions({

return sealedData;
},
});
};
};
}

Expand Down

0 comments on commit 4e15413

Please sign in to comment.