Shreyas Jadhav
Shreyas Jadhav

Reputation: 2571

Keystone: How to get context type based on defined lists?

the KeystoneContext type doesn't seem to give typescript support for context.query.[list]

what i tried

export const keystoneContext = ((globalThis as any).keystoneContext ||
  getContext(config, PrismaModule)) as KeystoneContext<{
  lists: typeof lists;
  prisma: PrismaModule.PrismaClient;
  session: any;
}>;

the error doesn't help what it exactly needs

Type '{ lists: { User: ListConfig<BaseListTypeInfo>; Site: ListConfig<BaseListTypeInfo>; Page: ListConfig<BaseListTypeInfo>; ... 7 more ...; DisplayedNFT: ListConfig<...>; }; prisma: PrismaClient<...>; session: any; }' does not satisfy the constraint 'BaseKeystoneTypeInfo'.
  Types of property 'lists' are incompatible.
    Type '{ User: ListConfig<BaseListTypeInfo>; Site: ListConfig<BaseListTypeInfo>; Page: ListConfig<BaseListTypeInfo>; ... 7 more ...; DisplayedNFT: ListConfig<...>; }' is not assignable to type 'Record<string, BaseListTypeInfo<any>>'.
      Property 'User' is incompatible with index signature.
        Type 'ListConfig<BaseListTypeInfo>' is missing the following properties from type 'BaseListTypeInfo<any>': key, item, inputs, prisma, all

Upvotes: -1

Views: 274

Answers (1)

Terry Gonguet
Terry Gonguet

Reputation: 1

Keystone 6 seems to generate type information into the node_modules/.keystone/types.ts file.

You can integrate these generated types along with your session data type like so:

// keystone.ts

import { TypeInfo } from ".keystone/types"
import { type Session } from "./my-session.ts"

export default config<TypeInfo<Session>>({
    db: { ... },
    lists: { ... },
    etc: { ... },
})

// my-session.ts

export type Session = {
    data: {
        isAdmin: boolean
    }
}

Any standalone function using the context can be defined like so:

import { Context } from ".keystone/types"
import { type Session } from "./my-session.ts"

function isAdmin(ctx: Context<Session>) {
    return !!ctx.session?.data.isAdmin
}

Upvotes: 0

Related Questions