From 1418aa81625c4820dfcefd8df6bcd0ae154e6dfa Mon Sep 17 00:00:00 2001 From: Tim Leslie Date: Fri, 23 Apr 2021 16:04:55 +1000 Subject: [PATCH] Use the DB list API where appropriate --- examples/ecommerce/mutations/addToCart.ts | 6 ++---- examples/ecommerce/mutations/checkout.ts | 3 +-- .../admin-ui/src/system/getAdminMetaSchema.ts | 7 +++---- packages-next/auth/src/gql/getBaseAuthSchema.ts | 7 ++----- .../auth/src/gql/getInitFirstItemSchema.ts | 9 +++------ .../auth/src/gql/getMagicAuthLinkSchema.ts | 13 ++++++++----- .../auth/src/gql/getPasswordResetSchema.ts | 14 ++++++++------ packages-next/auth/src/lib/createAuthToken.ts | 6 +++--- packages-next/auth/src/lib/findMatchingIdentity.ts | 9 +++------ packages-next/auth/src/lib/validateSecret.ts | 6 +++--- tests/api-tests/new-interfaces.test.ts | 2 +- 11 files changed, 37 insertions(+), 45 deletions(-) diff --git a/examples/ecommerce/mutations/addToCart.ts b/examples/ecommerce/mutations/addToCart.ts index f778fa7a662..7f668880a6f 100644 --- a/examples/ecommerce/mutations/addToCart.ts +++ b/examples/ecommerce/mutations/addToCart.ts @@ -24,19 +24,17 @@ async function addToCart( console.log(`There are already ${existingCartItem.quantity}, increment by 1!`); // 3. See if the current item is in their cart // 4. if itis, increment by 1 - return await context.lists.CartItem.updateOne({ + return await context.db.lists.CartItem.updateOne({ id: existingCartItem.id, data: { quantity: existingCartItem.quantity + 1 }, - resolveFields: false, }); } // 4. if it isnt, create a new cart item! - return await context.lists.CartItem.createOne({ + return await context.db.lists.CartItem.createOne({ data: { product: { connect: { id: productId } }, user: { connect: { id: sesh.itemId } }, }, - resolveFields: false, }); } diff --git a/examples/ecommerce/mutations/checkout.ts b/examples/ecommerce/mutations/checkout.ts index eb9c8fd8cf5..09cd142d597 100644 --- a/examples/ecommerce/mutations/checkout.ts +++ b/examples/ecommerce/mutations/checkout.ts @@ -75,14 +75,13 @@ async function checkout(root: any, { token }: Arguments, context: KeystoneContex }); console.log('gonna create the order'); // 5. Create the order and return it - const order = await context.lists.Order.createOne({ + const order = await context.db.lists.Order.createOne({ data: { total: charge.amount, charge: charge.id, items: { create: orderItems }, user: { connect: { id: userId } }, }, - resolveFields: false, }); console.log({ order }); // 6. Clean up any old cart item diff --git a/packages-next/admin-ui/src/system/getAdminMetaSchema.ts b/packages-next/admin-ui/src/system/getAdminMetaSchema.ts index f9b3bb75e3d..9951303dcc3 100644 --- a/packages-next/admin-ui/src/system/getAdminMetaSchema.ts +++ b/packages-next/admin-ui/src/system/getAdminMetaSchema.ts @@ -130,10 +130,9 @@ export function getAdminMetaSchema({ 'KeystoneAdminUIFieldMetaItemView.fieldMode cannot be resolved during the build process' ); } - const item = await context.sudo().lists[rootVal.listKey].findOne({ - where: { id: rootVal.itemId }, - resolveFields: false, - }); + const item = await context + .sudo() + .db.lists[rootVal.listKey].findOne({ where: { id: rootVal.itemId } }); const listConfig = config.lists[rootVal.listKey]; const sessionFunction = listConfig.fields[rootVal.fieldPath].config.ui?.itemView?.fieldMode ?? diff --git a/packages-next/auth/src/gql/getBaseAuthSchema.ts b/packages-next/auth/src/gql/getBaseAuthSchema.ts index 389e3d9b9b4..e82997b1c87 100644 --- a/packages-next/auth/src/gql/getBaseAuthSchema.ts +++ b/packages-next/auth/src/gql/getBaseAuthSchema.ts @@ -86,13 +86,10 @@ export function getBaseAuthSchema({ }, }, Query: { - async authenticatedItem(root, args, { session, lists }) { + async authenticatedItem(root, args, { session, db }) { if (typeof session?.itemId === 'string' && typeof session.listKey === 'string') { try { - return lists[session.listKey].findOne({ - where: { id: session.itemId }, - resolveFields: false, - }); + return db.lists[session.listKey].findOne({ where: { id: session.itemId } }); } catch (e) { return null; } diff --git a/packages-next/auth/src/gql/getInitFirstItemSchema.ts b/packages-next/auth/src/gql/getInitFirstItemSchema.ts index 89722394e66..6930de5a19c 100644 --- a/packages-next/auth/src/gql/getInitFirstItemSchema.ts +++ b/packages-next/auth/src/gql/getInitFirstItemSchema.ts @@ -45,17 +45,14 @@ export function getInitFirstItemSchema({ throw new Error('No session implementation available on context'); } - const itemAPI = context.sudo().lists[listKey]; - const count = await itemAPI.count({}); + const dbItemAPI = context.sudo().db.lists[listKey]; + const count = await dbItemAPI.count({}); if (count !== 0) { throw new Error('Initial items can only be created when no items exist in that list'); } // Update system state - const item = await itemAPI.createOne({ - data: { ...data, ...itemData }, - resolveFields: false, - }); + const item = await dbItemAPI.createOne({ data: { ...data, ...itemData } }); const sessionToken = await context.startSession({ listKey, itemId: item.id }); return { item, sessionToken }; }, diff --git a/packages-next/auth/src/gql/getMagicAuthLinkSchema.ts b/packages-next/auth/src/gql/getMagicAuthLinkSchema.ts index 8b2f7b319dc..a7f816ad02b 100644 --- a/packages-next/auth/src/gql/getMagicAuthLinkSchema.ts +++ b/packages-next/auth/src/gql/getMagicAuthLinkSchema.ts @@ -57,11 +57,16 @@ export function getMagicAuthLinkSchema({ Mutation: { async [gqlNames.sendItemMagicAuthLink](root: any, args: { [P in I]: string }, context) { const list = context.keystone.lists[listKey]; - const itemAPI = context.sudo().lists[listKey]; + const dbItemAPI = context.sudo().db.lists[listKey]; const tokenType = 'magicAuth'; const identity = args[identityField]; - const result = await createAuthToken(identityField, protectIdentities, identity, itemAPI); + const result = await createAuthToken( + identityField, + protectIdentities, + identity, + dbItemAPI + ); // Note: `success` can be false with no code // If protectIdentities === true then result.code will *always* be undefined. @@ -79,14 +84,13 @@ export function getMagicAuthLinkSchema({ if (result.success) { // Save the token and related info back to the item const { token, itemId } = result; - await itemAPI.updateOne({ + await dbItemAPI.updateOne({ id: `${itemId}`, data: { [`${tokenType}Token`]: token, [`${tokenType}IssuedAt`]: new Date().toISOString(), [`${tokenType}RedeemedAt`]: null, }, - resolveFields: false, }); await magicAuthLink.sendToken({ itemId, identity, token, context }); @@ -131,7 +135,6 @@ export function getMagicAuthLinkSchema({ await itemAPI.updateOne({ id: result.item.id, data: { [`${tokenType}RedeemedAt`]: new Date().toISOString() }, - resolveFields: false, }); const sessionToken = await context.startSession({ listKey, itemId: result.item.id }); diff --git a/packages-next/auth/src/gql/getPasswordResetSchema.ts b/packages-next/auth/src/gql/getPasswordResetSchema.ts index 5f0dd12a314..094c31edc0b 100644 --- a/packages-next/auth/src/gql/getPasswordResetSchema.ts +++ b/packages-next/auth/src/gql/getPasswordResetSchema.ts @@ -62,11 +62,16 @@ export function getPasswordResetSchema({ Mutation: { async [gqlNames.sendItemPasswordResetLink](root: any, args: { [P in I]: string }, context) { const list = context.keystone.lists[listKey]; - const itemAPI = context.sudo().lists[listKey]; + const dbItemAPI = context.sudo().db.lists[listKey]; const tokenType = 'passwordReset'; const identity = args[identityField]; - const result = await createAuthToken(identityField, protectIdentities, identity, itemAPI); + const result = await createAuthToken( + identityField, + protectIdentities, + identity, + dbItemAPI + ); // Note: `success` can be false with no code // If protectIdentities === true then result.code will *always* be undefined. @@ -84,14 +89,13 @@ export function getPasswordResetSchema({ if (result.success) { // Save the token and related info back to the item const { token, itemId } = result; - await itemAPI.updateOne({ + await dbItemAPI.updateOne({ id: `${itemId}`, data: { [`${tokenType}Token`]: token, [`${tokenType}IssuedAt`]: new Date().toISOString(), [`${tokenType}RedeemedAt`]: null, }, - resolveFields: false, }); await passwordResetLink.sendToken({ itemId, identity, token, context }); @@ -136,7 +140,6 @@ export function getPasswordResetSchema({ await itemAPI.updateOne({ id: itemId, data: { [`${tokenType}RedeemedAt`]: new Date().toISOString() }, - resolveFields: false, }); // Save the provided secret. Do this as a separate step as password validation @@ -145,7 +148,6 @@ export function getPasswordResetSchema({ await itemAPI.updateOne({ id: itemId, data: { [secretField]: args[secretField] }, - resolveFields: false, }); return null; diff --git a/packages-next/auth/src/lib/createAuthToken.ts b/packages-next/auth/src/lib/createAuthToken.ts index 7ec3c777a10..ad9f5aee0d5 100644 --- a/packages-next/auth/src/lib/createAuthToken.ts +++ b/packages-next/auth/src/lib/createAuthToken.ts @@ -1,5 +1,5 @@ import { randomBytes } from 'crypto'; -import type { KeystoneListsAPI } from '@keystone-next/types'; +import type { KeystoneDbAPI } from '@keystone-next/types'; import { AuthTokenRequestErrorCode } from '../types'; import { findMatchingIdentity } from './findMatchingIdentity'; @@ -16,12 +16,12 @@ export async function createAuthToken( identityField: string, protectIdentities: boolean, identity: string, - itemAPI: KeystoneListsAPI[string] + dbItemAPI: KeystoneDbAPI[string] ): Promise< | { success: false; code?: AuthTokenRequestErrorCode } | { success: true; itemId: string | number; token: string } > { - const match = await findMatchingIdentity(identityField, identity, itemAPI); + const match = await findMatchingIdentity(identityField, identity, dbItemAPI); // Identity failures with helpful errors (unless it would violate our protectIdentities config) if (match.success) { return { success: true, itemId: match.item.id, token: generateToken(20) }; diff --git a/packages-next/auth/src/lib/findMatchingIdentity.ts b/packages-next/auth/src/lib/findMatchingIdentity.ts index 4bc6d3b5fd5..5c39b867b23 100644 --- a/packages-next/auth/src/lib/findMatchingIdentity.ts +++ b/packages-next/auth/src/lib/findMatchingIdentity.ts @@ -1,19 +1,16 @@ -import type { KeystoneListsAPI } from '@keystone-next/types'; +import type { KeystoneDbAPI } from '@keystone-next/types'; import { AuthTokenRequestErrorCode } from '../types'; export async function findMatchingIdentity( identityField: string, identity: string, - itemAPI: KeystoneListsAPI[string] + dbItemAPI: KeystoneDbAPI[string] ): Promise< | { success: false; code: AuthTokenRequestErrorCode } | { success: true; item: { id: any; [prop: string]: any } } > { - const items = await itemAPI.findMany({ - where: { [identityField]: identity }, - resolveFields: false, - }); + const items = await dbItemAPI.findMany({ where: { [identityField]: identity } }); // Identity failures with helpful errors let code: AuthTokenRequestErrorCode | undefined; diff --git a/packages-next/auth/src/lib/validateSecret.ts b/packages-next/auth/src/lib/validateSecret.ts index 24b3251d6a7..3e24eb03642 100644 --- a/packages-next/auth/src/lib/validateSecret.ts +++ b/packages-next/auth/src/lib/validateSecret.ts @@ -1,4 +1,4 @@ -import type { KeystoneListsAPI } from '@keystone-next/types'; +import type { KeystoneDbAPI } from '@keystone-next/types'; import { PasswordAuthErrorCode } from '../types'; import { findMatchingIdentity } from './findMatchingIdentity'; @@ -9,12 +9,12 @@ export async function validateSecret( secretField: string, protectIdentities: boolean, secret: string, - itemAPI: KeystoneListsAPI[string] + dbItemAPI: KeystoneDbAPI[string] ): Promise< | { success: false; code: PasswordAuthErrorCode } | { success: true; item: { id: any; [prop: string]: any } } > { - const match = await findMatchingIdentity(identityField, identity, itemAPI); + const match = await findMatchingIdentity(identityField, identity, dbItemAPI); // Identity failures with helpful errors let code: PasswordAuthErrorCode | undefined; if (!match.success) { diff --git a/tests/api-tests/new-interfaces.test.ts b/tests/api-tests/new-interfaces.test.ts index 901c9b152a0..b67683f4123 100644 --- a/tests/api-tests/new-interfaces.test.ts +++ b/tests/api-tests/new-interfaces.test.ts @@ -19,7 +19,7 @@ multiAdapterRunners().map(({ runner, provider }) => test( 'Smoke test', runner(setupKeystone, async ({ context }) => { - const users = await context.lists.User.findMany({ resolveFields: false }); + const users = await context.db.lists.User.findMany({}); expect(users).toEqual([]); }) );