chore: implements new typing into create and find operations

This commit is contained in:
James
2023-01-17 10:22:17 -05:00
parent 0af29ff4db
commit ed998598df
7 changed files with 37 additions and 32 deletions

View File

@@ -1,5 +1,5 @@
import crypto from 'crypto';
import { Config as GeneratedTypes } from 'payload/generated-types';
import executeAccess from '../../auth/executeAccess';
import sanitizeInternalFields from '../../utilities/sanitizeInternalFields';
@@ -17,19 +17,21 @@ import { afterChange } from '../../fields/hooks/afterChange';
import { afterRead } from '../../fields/hooks/afterRead';
import { generateFileData } from '../../uploads/generateFileData';
export type Arguments = {
export type Arguments<T extends { [field: string | number | symbol]: unknown }> = {
collection: Collection
req: PayloadRequest
depth?: number
disableVerificationEmail?: boolean
overrideAccess?: boolean
showHiddenFields?: boolean
data: Record<string, unknown>
data: T
overwriteExistingFiles?: boolean
draft?: boolean
}
async function create(incomingArgs: Arguments): Promise<Document> {
async function create<TSlug extends keyof GeneratedTypes['collections']>(
incomingArgs: Arguments<GeneratedTypes['collections'][TSlug]>,
): Promise<GeneratedTypes['collections'][TSlug]> {
let args = incomingArgs;
// /////////////////////////////////////
@@ -159,7 +161,7 @@ async function create(incomingArgs: Arguments): Promise<Document> {
// beforeChange - Fields
// /////////////////////////////////////
const resultWithLocales = await beforeChange({
const resultWithLocales = await beforeChange<Record<string, unknown>>({
data,
doc: {},
docWithLocales: {},

View File

@@ -2,7 +2,7 @@ import { Where } from '../../types';
import { PayloadRequest } from '../../express/types';
import executeAccess from '../../auth/executeAccess';
import sanitizeInternalFields from '../../utilities/sanitizeInternalFields';
import { Collection, TypeWithID } from '../config/types';
import { Collection } from '../config/types';
import { PaginatedDocs } from '../../mongoose/types';
import { hasWhereAccessResult } from '../../auth/types';
import flattenWhereConstraints from '../../utilities/flattenWhereConstraints';
@@ -28,7 +28,9 @@ export type Arguments = {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function find<T extends TypeWithID = any>(incomingArgs: Arguments): Promise<PaginatedDocs<T>> {
async function find<T extends Record<string, unknown>>(
incomingArgs: Arguments,
): Promise<PaginatedDocs<T>> {
let args = incomingArgs;
// /////////////////////////////////////

View File

@@ -23,7 +23,9 @@ export type Arguments = {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function findByID<T extends Record<string, unknown>>(incomingArgs: Arguments): Promise<T> {
async function findByID<T extends Record<string, unknown>>(
incomingArgs: Arguments,
): Promise<T> {
let args = incomingArgs;
// /////////////////////////////////////

View File

@@ -1,3 +1,4 @@
import { Config as GeneratedTypes } from 'payload/generated-types';
import { UploadedFile } from 'express-fileupload';
import { Payload } from '../../../payload';
import { PayloadRequest } from '../../../express/types';
@@ -8,9 +9,9 @@ import { getDataLoader } from '../../dataloader';
import { File } from '../../../uploads/types';
import i18n from '../../../translations/init';
export type Options<T> = {
collection: string
data: Record<string, unknown>
export type Options<TSlug extends keyof GeneratedTypes['collections']> = {
collection: TSlug
data: GeneratedTypes['collections'][TSlug]
depth?: number
locale?: string
fallbackLocale?: string
@@ -25,7 +26,10 @@ export type Options<T> = {
draft?: boolean
}
export default async function createLocal<T = any>(payload: Payload, options: Options<T>): Promise<T> {
export default async function createLocal<TSlug extends keyof GeneratedTypes['collections']>(
payload: Payload,
options: Options<TSlug>,
): Promise<GeneratedTypes['collections'][TSlug]> {
const {
collection: collectionSlug,
depth,
@@ -60,7 +64,7 @@ export default async function createLocal<T = any>(payload: Payload, options: Op
if (!req.t) req.t = req.i18n.t;
if (!req.payloadDataLoader) req.payloadDataLoader = getDataLoader(req);
return create({
return create<TSlug>({
depth,
data,
collection,

View File

@@ -1,4 +1,4 @@
import { TypeWithID } from '../../config/types';
import { Config as GeneratedTypes } from 'payload/generated-types';
import { PaginatedDocs } from '../../../mongoose/types';
import { Document, Where } from '../../../types';
import { Payload } from '../../../payload';
@@ -7,8 +7,8 @@ import find from '../find';
import { getDataLoader } from '../../dataloader';
import i18n from '../../../translations/init';
export type Options = {
collection: string
export type Options<T extends keyof GeneratedTypes['collections']> = {
collection: T
depth?: number
currentDepth?: number
page?: number
@@ -27,7 +27,10 @@ export type Options = {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default async function findLocal<T extends TypeWithID = any>(payload: Payload, options: Options): Promise<PaginatedDocs<T>> {
export default async function findLocal<T extends keyof GeneratedTypes['collections']>(
payload: Payload,
options: Options<T>,
): Promise<PaginatedDocs<GeneratedTypes['collections'][T]>> {
const {
collection: collectionSlug,
depth,
@@ -61,7 +64,7 @@ export default async function findLocal<T extends TypeWithID = any>(payload: Pay
if (typeof user !== 'undefined') req.user = user;
return find({
return find<GeneratedTypes['collections'][T]>({
depth,
currentDepth,
sort,

View File

@@ -211,9 +211,9 @@ export class BasePayload<TGeneratedTypes extends GeneratedTypes> {
* @param options
* @returns created document
*/
create = async <T = any>(options: CreateOptions<T>): Promise<T> => {
create = async <T extends keyof TGeneratedTypes['collections']>(options: CreateOptions<T>): Promise<TGeneratedTypes['collections'][T]> => {
const { create } = localOperations;
return create(this, options);
return create<T>(this, options);
}
/**
@@ -221,9 +221,9 @@ export class BasePayload<TGeneratedTypes extends GeneratedTypes> {
* @param options
* @returns documents satisfying query
*/
find = async <T extends TypeWithID = any>(options: FindOptions): Promise<PaginatedDocs<T>> => {
find = async <T extends keyof TGeneratedTypes['collections']>(options: FindOptions<T>): Promise<PaginatedDocs<TGeneratedTypes['collections'][T]>> => {
const { find } = localOperations;
return find(this, options);
return find<T>(this, options);
}
findGlobal = async <T extends GlobalTypeWithID = any>(options: FindGlobalOptions): Promise<T> => {

View File

@@ -2,10 +2,9 @@ import { AccessResult } from '../../config/types';
import { Where } from '../../types';
import { Payload } from '../../payload';
import { PaginatedDocs } from '../../mongoose/types';
import { Collection, CollectionModel, TypeWithID } from '../../collections/config/types';
import { Collection, CollectionModel } from '../../collections/config/types';
import { hasWhereAccessResult } from '../../auth';
import { appendVersionToQueryKey } from './appendVersionToQueryKey';
import sanitizeInternalFields from '../../utilities/sanitizeInternalFields';
import replaceWithDraftIfAvailable from './replaceWithDraftIfAvailable';
type AggregateVersion<T> = {
@@ -33,7 +32,7 @@ type Args = {
where: Where
}
export const mergeDrafts = async <T extends TypeWithID>({
export const mergeDrafts = async <T extends Record<string, unknown>>({
accessResult,
collection,
locale,
@@ -51,8 +50,6 @@ export const mergeDrafts = async <T extends TypeWithID>({
return newMap;
}, {}));
console.log({ mainCollectionMatchMap });
// Query the versions collection with a version-specific query
const VersionModel = payload.versions[collection.config.slug] as CollectionModel;
@@ -135,9 +132,6 @@ export const mergeDrafts = async <T extends TypeWithID>({
return newMap;
}, {}));
console.log({ versionCollectionMatchMap });
console.log({ includedParentIDs });
// Now we need to explicitly exclude any parent matches that have newer versions
// which did NOT appear in the versions query
const excludedParentIDs = await Promise.all(Object.entries(mainCollectionMatchMap).map(async ([parentDocID, parentDocUpdatedAt]) => {
@@ -202,8 +196,6 @@ export const mergeDrafts = async <T extends TypeWithID>({
});
}
console.log({ finalQueryToBuild: JSON.stringify(finalQueryToBuild) });
const finalQuery = await collection.Model.buildQuery(finalQueryToBuild, locale);
let result = await collection.Model.paginate(finalQuery, paginationOptions);