Compare commits

..

1 Commits

Author SHA1 Message Date
Elliot DeNolf
67e9306f7a chore(release): v3.0.0-alpha.10 [skip ci] 2024-03-04 11:37:07 -05:00
1924 changed files with 36381 additions and 37536 deletions

View File

@@ -4,7 +4,7 @@ on:
pull_request:
types: [ opened, reopened, synchronize ]
push:
branches: ['main', 'alpha']
branches: ['main', 'feat/next-poc']
jobs:
changes:

6
.gitignore vendored
View File

@@ -8,15 +8,12 @@ test-results
.devcontainer
.localstack
/migrations
/media
.localstack
.turbo
.turbo
# Ignore test directory media folder/files
/media
/versions
# Created by https://www.toptal.com/developers/gitignore/api/node,macos,windows,webstorm,sublimetext,visualstudiocode
# Edit at https://www.toptal.com/developers/gitignore?templates=node,macos,windows,webstorm,sublimetext,visualstudiocode
@@ -288,4 +285,3 @@ $RECYCLE.BIN/
# End of https://www.toptal.com/developers/gitignore/api/node,macos,windows,webstorm,sublimetext,visualstudiocode
/build
.swc

View File

@@ -1,15 +0,0 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Playwright test" type="JavaScriptTestRunnerPlaywright">
<node-interpreter value="project" />
<playwright-package value="$PROJECT_DIR$/node_modules/playwright" />
<working-dir value="$PROJECT_DIR$" />
<envs />
<scope-kind value="TEST" />
<test-file value="$PROJECT_DIR$/test/_community/e2e.spec.ts" />
<test-names>
<test-name value="Admin Panel" />
<test-name value="example test" />
</test-names>
<method v="2" />
</configuration>
</component>

View File

@@ -9,4 +9,3 @@
**/node_modules
**/temp
**/docs/**
tsconfig.json

15
.swcrc
View File

@@ -1,15 +0,0 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": "inline",
"jsc": {
"target": "esnext",
"parser": {
"syntax": "typescript",
"tsx": true,
"dts": true
}
},
"module": {
"type": "es6"
}
}

20
.vscode/launch.json vendored
View File

@@ -3,14 +3,13 @@
// Hover to view descriptions of existing attributes.
"configurations": [
{
"command": "pnpm generate:types",
"name": "Generate Types CLI",
"command": "pnpm dev",
"name": "Run Dev 3.0",
"request": "launch",
"type": "node-terminal",
"cwd": "${workspaceFolder}"
"type": "node-terminal"
},
{
"command": "pnpm run dev _community -- --no-turbo",
"command": "pnpm run dev _community",
"cwd": "${workspaceFolder}",
"name": "Run Dev Community",
"request": "launch",
@@ -109,6 +108,17 @@
"request": "launch",
"type": "node-terminal"
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts generate:types",
"env": {
"PAYLOAD_CONFIG_PATH": "test/_community/config.ts",
"DISABLE_SWC": "true" // SWC messes up debugging the bin scripts
},
"name": "Generate Types CLI",
"outputCapture": "std",
"request": "launch",
"type": "node-terminal"
},
{
"command": "ts-node ./packages/payload/src/bin/index.ts migrate:status",
"env": {

22
.vscode/settings.json vendored
View File

@@ -40,5 +40,25 @@
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
}
}
},
"workbench.colorCustomizations": {
"activityBar.activeBackground": "#8cb5b6",
"activityBar.background": "#8cb5b6",
"activityBar.foreground": "#15202b",
"activityBar.inactiveForeground": "#15202b99",
"activityBarBadge.background": "#9c639b",
"activityBarBadge.foreground": "#e7e7e7",
"commandCenter.border": "#15202b99",
"sash.hoverBorder": "#8cb5b6",
"statusBar.background": "#6da1a2",
"statusBar.foreground": "#15202b",
"statusBarItem.hoverBackground": "#568586",
"statusBarItem.remoteBackground": "#6da1a2",
"statusBarItem.remoteForeground": "#15202b",
"titleBar.activeBackground": "#6da1a2",
"titleBar.activeForeground": "#15202b",
"titleBar.inactiveBackground": "#6da1a299",
"titleBar.inactiveForeground": "#15202b99"
},
"peacock.color": "#6da1a2"
}

View File

@@ -1,17 +0,0 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
import config from '@payload-config'
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import { NotFoundView } from '@payloadcms/next/views/NotFound/index.js'
type Args = {
params: {
segments: string[]
}
searchParams: {
[key: string]: string | string[]
}
}
const NotFound = ({ params, searchParams }: Args) => NotFoundView({ config, params, searchParams })
export default NotFound

View File

@@ -1,7 +1,7 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
import config from '@payload-config'
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import { RootPage, generatePageMetadata } from '@payloadcms/next/views/Root/index.js'
import { RootPage } from '@payloadcms/next/views/Root/index'
type Args = {
params: {
@@ -12,9 +12,6 @@ type Args = {
}
}
export const generateMetadata = ({ params, searchParams }: Args) =>
generatePageMetadata({ config, params, searchParams })
const Page = ({ params, searchParams }: Args) => RootPage({ config, params, searchParams })
export default Page

View File

@@ -1,7 +1,7 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { REST_DELETE, REST_GET, REST_PATCH, REST_POST } from '@payloadcms/next/routes/index.js'
import { REST_GET, REST_DELETE, REST_PATCH, REST_POST } from '@payloadcms/next/routes'
export const GET = REST_GET(config)
export const POST = REST_POST(config)

View File

@@ -0,0 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { GET_STATIC_FILE } from '@payloadcms/next/routes'
export const GET = GET_STATIC_FILE(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { GRAPHQL_PLAYGROUND_GET } from '@payloadcms/next/routes/index.js'
import { GRAPHQL_PLAYGROUND_GET } from '@payloadcms/next/routes'
export const GET = GRAPHQL_PLAYGROUND_GET(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
/* DO NOT MODIFY it because it could be re-written at any time. */
import config from '@payload-config'
import { GRAPHQL_POST } from '@payloadcms/next/routes/index.js'
import { GRAPHQL_POST } from '@payloadcms/next/routes'
export const POST = GRAPHQL_POST(config)

View File

@@ -1,6 +1,6 @@
/* THIS FILE WAS GENERATED AUTOMATICALLY BY PAYLOAD. */
import configPromise from '@payload-config'
import { RootLayout } from '@payloadcms/next/layouts/Root/index.js'
import { RootLayout } from '@payloadcms/next/layouts/Root/index'
/* DO NOT MODIFY IT BECAUSE IT COULD BE REWRITTEN AT ANY TIME. */
import React from 'react'

View File

@@ -1,4 +1,9 @@
export const GET = () => {
export const GET = async () => {
console.log('1')
console.log('1')
console.log('1')
console.log('1')
console.log('1')
return Response.json({
hello: 'elliot',
})

View File

@@ -292,11 +292,13 @@ For auth-enabled Collections, this hook runs after successful `forgotPassword` o
```ts
import { CollectionAfterForgotPasswordHook } from 'payload/types'
const afterForgotPasswordHook: CollectionAfterForgotPasswordHook = async ({
args, // arguments passed into the operation
context,
collection, // The collection which this hook is being run on
}) => {...}
const afterLoginHook: CollectionAfterForgotPasswordHook = async ({
req, // full express request
user, // user being logged in
token, // user token
}) => {
return user
}
```
## TypeScript

View File

@@ -290,5 +290,5 @@ If you&apos;ve configured tests for your package, integrate them into your workf
The best way to share and allow others to use your plugin once it is complete is to publish an NPM package. This process is straightforward and well documented, find out more about [creating and publishing a NPM package here](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/).
##### Add payload-plugin topic tag:
Apply the tag **payload-plugin** to your GitHub repository. This will boost the visibility of your plugin and ensure it gets listed with [existing payload plugins](https://github.com/topics/payload-plugin).
##### Use [Semantic Versioning](https://semver.org/) (SemVer):
With the SemVer system you release version numbers that reflect the nature of changes (major, minor, patch). Ensure all major versions reference their Payload compatibility.
##### Use [Semantic Versioning](https://semver.org/) (SemVar):
With the SemVar system you release version numbers that reflect the nature of changes (major, minor, patch). Ensure all major versions reference their Payload compatibility.

View File

@@ -1 +0,0 @@
export default {}

View File

@@ -6,13 +6,11 @@
// })
const customJestConfig = {
extensionsToTreatAsEsm: ['.ts', '.tsx'],
globalSetup: './test/jest.setup.ts',
moduleNameMapper: {
'\\.(css|scss)$': '<rootDir>/test/helpers/mocks/emptyModule.js',
'\\.(css|scss)$': '<rootDir>/packages/payload/src/bundlers/mocks/emptyModule.js',
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
'<rootDir>/test/helpers/mocks/fileMock.js',
'^(\\.{1,2}/.*)\\.js$': '$1',
'<rootDir>/packages/payload/src/bundlers/mocks/fileMock.js',
},
testEnvironment: 'node',
testMatch: ['<rootDir>/packages/payload/src/**/*.spec.ts', '<rootDir>/test/**/*int.spec.ts'],
@@ -24,4 +22,4 @@ const customJestConfig = {
}
// module.exports = createJestConfig(customJestConfig)
export default customJestConfig
module.exports = customJestConfig

10
next.config.js Normal file
View File

@@ -0,0 +1,10 @@
const { withPayload } = require('./packages/next/src/withPayload')
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer(
withPayload({
reactStrictMode: false,
}),
)

View File

@@ -1,30 +0,0 @@
import bundleAnalyzer from '@next/bundle-analyzer'
import withPayload from './packages/next/src/withPayload.js'
const withBundleAnalyzer = bundleAnalyzer({
enabled: process.env.ANALYZE === 'true',
})
export default withBundleAnalyzer(
withPayload({
reactStrictMode: false,
async redirects() {
return [
{
destination: '/admin',
permanent: true,
source: '/',
},
]
},
webpack: (webpackConfig) => {
webpackConfig.resolve.extensionAlias = {
'.cjs': ['.cts', '.cjs'],
'.js': ['.ts', '.tsx', '.js', '.jsx'],
'.mjs': ['.mts', '.mjs'],
}
return webpackConfig
},
}),
)

View File

@@ -1,19 +1,16 @@
{
"name": "payload-monorepo",
"version": "3.0.0-alpha.42",
"version": "3.0.0-alpha.10",
"private": true,
"type": "module",
"workspaces:": [
"packages/*"
],
"scripts": {
"build": "pnpm run build:core",
"obliterate-playwright-cache": "rm -rf ~/Library/Caches/ms-playwright && find /System/Volumes/Data/private/var/folders -type d -name 'playwright*' -exec rm -rf {} ++ && npx playwright install",
"build:all": "turbo build",
"build:core": "turbo build --filter \"!@payloadcms/plugin-*\"",
"build:plugins": "turbo build --filter \"@payloadcms/plugin-*\"",
"build:app": "next build",
"build:app:analyze": "cross-env ANALYZE=true next build",
"build:create-payload-app": "turbo build --filter create-payload-app",
"build:db-mongodb": "turbo build --filter db-mongodb",
"build:db-postgres": "turbo build --filter db-postgres",
@@ -38,18 +35,15 @@
"build:ui": "turbo build --filter ui",
"clean": "turbo clean",
"clean:cache": "rimraf node_modules/.cache && rimraf packages/payload/node_modules/.cache && rimraf .next",
"clean:build": "find . \\( -type d \\( -name dist -o -name .cache -o -name .next -o -name .turbo \\) -o -type f -name tsconfig.tsbuildinfo \\) -not -path '*/node_modules/*' -exec rm -rf {} +",
"clean:all": "find . \\( -type d \\( -name node_modules -o -name dist -o -name .cache -o -name .next -o -name .turbo \\) -o -type f -name tsconfig.tsbuildinfo \\) -exec rm -rf {} +",
"dev": "cross-env node --no-deprecation ./test/dev.js",
"devsafe": "rm -rf .next && cross-env node --no-deprecation ./test/dev.js",
"dev:generate-graphql-schema": "cross-env NODE_OPTIONS=--no-deprecation tsx ./test/generateGraphQLSchema.ts",
"dev:generate-types": "cross-env NODE_OPTIONS=--no-deprecation tsx ./test/generateTypes.ts",
"clean:all": "find . \\( -type d \\( -name node_modules -o -name dist -o -name .cache \\) -o -type f -name tsconfig.tsbuildinfo \\) -exec rm -rf {} +",
"dev": "cross-env node ./test/dev.js",
"dev:generate-graphql-schema": "ts-node -T ./test/generateGraphQLSchema.ts",
"dev:generate-types": "ts-node -T ./test/generateTypes.ts",
"dev:postgres": "pnpm --filter payload run dev:postgres",
"docker:restart": "pnpm docker:stop --remove-orphans && pnpm docker:start",
"docker:start": "docker-compose -f packages/plugin-cloud-storage/docker-compose.yml up -d",
"docker:stop": "docker-compose -f packages/plugin-cloud-storage/docker-compose.yml down",
"fix": "eslint \"packages/**/*.ts\" --fix",
"generate:types": "PAYLOAD_CONFIG_PATH=./test/_community/config.ts node --no-deprecation ./packages/payload/bin.js generate:types",
"lint": "eslint \"packages/**/*.ts\"",
"lint-staged": "lint-staged",
"prepare": "husky install",
@@ -59,12 +53,12 @@
"release:alpha": "tsx ./scripts/release.ts --bump prerelease --tag alpha",
"release:beta": "tsx ./scripts/release.ts --bump prerelease --tag beta",
"test": "pnpm test:int && pnpm test:components && pnpm test:e2e",
"test:components": "cross-env NODE_OPTIONS=--no-deprecation jest --config=jest.components.config.js",
"test:e2e": "NODE_OPTIONS=--no-deprecation npx playwright install --with-deps chromium && NODE_OPTIONS=--no-deprecation tsx ./test/runE2E.ts",
"test:e2e:debug": "cross-env NODE_OPTIONS=--no-deprecation PWDEBUG=1 DISABLE_LOGGING=true playwright test",
"test:e2e:headed": "cross-env NODE_OPTIONS=--no-deprecation DISABLE_LOGGING=true playwright test --headed",
"test:int:postgres": "cross-env NODE_OPTIONS=--no-deprecation PAYLOAD_DATABASE=postgres DISABLE_LOGGING=true jest --forceExit --detectOpenHandles",
"test:int": "cross-env NODE_OPTIONS=--no-deprecation DISABLE_LOGGING=true jest --forceExit --detectOpenHandles",
"test:components": "cross-env jest --config=jest.components.config.js",
"test:e2e": "npx playwright install --with-deps chromium && ts-node -T ./test/runE2E.ts",
"test:e2e:debug": "cross-env PWDEBUG=1 DISABLE_LOGGING=true playwright test",
"test:e2e:headed": "cross-env DISABLE_LOGGING=true playwright test --headed",
"test:int:postgres": "cross-env PAYLOAD_DATABASE=postgres DISABLE_LOGGING=true jest --forceExit --detectOpenHandles",
"test:int": "cross-env DISABLE_LOGGING=true jest --forceExit --detectOpenHandles",
"translateNewKeys": "pnpm --filter payload run translateNewKeys"
},
"devDependencies": {
@@ -72,18 +66,19 @@
"@next/bundle-analyzer": "^14.1.0",
"@octokit/core": "^5.1.0",
"@payloadcms/eslint-config": "workspace:*",
"@playwright/test": "^1.42.1",
"@playwright/test": "1.40.1",
"@swc/cli": "^0.1.62",
"@swc/jest": "0.2.36",
"@testing-library/jest-dom": "6.4.2",
"@testing-library/react": "14.2.1",
"@swc/jest": "0.2.29",
"@swc/register": "0.1.10",
"@testing-library/jest-dom": "5.17.0",
"@testing-library/react": "13.4.0",
"@types/concat-stream": "^2.0.1",
"@types/conventional-changelog": "^3.1.4",
"@types/conventional-changelog-core": "^4.2.5",
"@types/conventional-changelog-preset-loader": "^2.3.4",
"@types/conventional-changelog-writer": "^4.0.10",
"@types/fs-extra": "^11.0.2",
"@types/jest": "29.5.12",
"@types/jest": "29.5.7",
"@types/minimist": "1.2.2",
"@types/node": "20.5.7",
"@types/prompts": "^2.4.5",
@@ -91,9 +86,9 @@
"@types/react": "18.2.15",
"@types/semver": "^7.5.3",
"@types/shelljs": "0.8.12",
"@types/testing-library__jest-dom": "5.14.8",
"add-stream": "^1.0.0",
"chalk": "^4.1.2",
"comment-json": "^4.2.3",
"concat-stream": "^2.0.0",
"conventional-changelog": "^5.1.0",
"conventional-changelog-conventionalcommits": "^7.0.2",
@@ -105,6 +100,7 @@
"dotenv": "8.6.0",
"drizzle-orm": "0.29.4",
"execa": "5.1.1",
"express": "4.18.2",
"form-data": "3.0.1",
"fs-extra": "10.1.0",
"get-port": "5.1.1",
@@ -119,13 +115,11 @@
"lint-staged": "^14.0.1",
"minimist": "1.2.8",
"mongodb-memory-server": "^9",
"next": "14.1.2",
"next": "14.1.1-canary.26",
"node-mocks-http": "^1.14.1",
"nodemon": "3.0.3",
"pino": "8.15.0",
"pino-pretty": "10.2.0",
"playwright": "^1.42.1",
"playwright-core": "^1.42.1",
"prettier": "^3.0.3",
"prompts": "2.4.2",
"qs": "6.11.2",
@@ -134,15 +128,15 @@
"read-stream": "^2.1.1",
"rimraf": "3.0.2",
"semver": "^7.5.4",
"sharp": "0.32.6",
"sharp": "0.33.2",
"shelljs": "0.8.5",
"simple-git": "^3.20.0",
"slash": "3.0.0",
"slate": "0.91.4",
"tempfile": "^3.0.0",
"ts-node": "10.9.1",
"ts-node": "10.9.2",
"tsx": "^4.7.1",
"turbo": "^1.12.5",
"turbo": "^1.12.4",
"typescript": "5.2.2",
"uuid": "^9.0.1",
"yocto-queue": "^1.0.0"
@@ -173,6 +167,7 @@
"graphql": "^16.8.1",
"react": "$react",
"react-dom": "$react-dom",
"ts-node": "$ts-node",
"typescript": "$typescript"
},
"allowedDeprecatedVersions": {
@@ -180,6 +175,5 @@
"abab": "2",
"domexception": "4"
}
},
"packageManager": "pnpm@8.15.4+sha256.cea6d0bdf2de3a0549582da3983c70c92ffc577ff4410cbf190817ddc35137c2"
}
}

View File

@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": true,
"sourceMaps": "inline",
"jsc": {
"target": "esnext",
"parser": {

View File

@@ -7,7 +7,7 @@
},
"scripts": {
"build": "pnpm copyfiles && pnpm build:swc",
"copyfiles": "copyfiles -u 2 \"../../app/(payload)/**\" \"dist\"",
"copyfiles": "copyfiles -u 4 \"../next/src/app/(payload)/**\" \"dist/app\"",
"build:swc": "swc ./src -d ./dist --config-file .swcrc",
"clean": "rimraf {dist,*.tsbuildinfo}",
"test": "jest",
@@ -23,9 +23,7 @@
"arg": "^5.0.0",
"chalk": "^4.1.0",
"command-exists": "^1.2.9",
"comment-json": "^4.2.3",
"degit": "^2.8.4",
"detect-package-manager": "^3.0.1",
"execa": "^5.0.0",
"figures": "^3.2.0",
"fs-extra": "^9.0.1",

View File

@@ -1,88 +1,16 @@
import type { CompilerOptions } from 'typescript'
import chalk from 'chalk'
import * as CommentJson from 'comment-json'
import { detect } from 'detect-package-manager'
import execa from 'execa'
import fs from 'fs'
import fse from 'fs-extra'
import globby from 'globby'
import path from 'path'
import type { CliArgs } from '../types'
import { copyRecursiveSync } from '../utils/copy-recursive-sync'
import { error, info, debug as origDebug, success, warning } from '../utils/log'
import { error, info, debug as origDebug, success } from '../utils/log'
type InitNextArgs = Pick<CliArgs, '--debug'> & {
projectDir?: string
useDistFiles?: boolean
}
type InitNextResult = { reason?: string; success: boolean; userAppDir?: string }
export async function initNext(args: InitNextArgs): Promise<InitNextResult> {
args.projectDir = args.projectDir || process.cwd()
const { projectDir } = args
const templateResult = await applyPayloadTemplateFiles(args)
if (!templateResult.success) return templateResult
const { success: installSuccess } = await installDeps(projectDir)
if (!installSuccess) {
return { ...templateResult, reason: 'Failed to install dependencies', success: false }
}
// Create or find payload.config.ts
const createConfigResult = findOrCreatePayloadConfig(projectDir)
if (!createConfigResult.success) {
return { ...templateResult, ...createConfigResult }
}
// Add `@payload-config` to tsconfig.json `paths`
await addPayloadConfigToTsConfig(projectDir)
// Output directions for user to update next.config.js
const withPayloadMessage = `
${chalk.bold(`Wrap your existing next.config.js with the withPayload function. Here is an example:`)}
const { withPayload } = require("@payloadcms/next");
const nextConfig = {
// Your Next.js config
};
module.exports = withPayload(nextConfig);
`
console.log(withPayloadMessage)
return templateResult
}
async function addPayloadConfigToTsConfig(projectDir: string) {
const tsConfigPath = path.resolve(projectDir, 'tsconfig.json')
const userTsConfigContent = await fse.readFile(tsConfigPath, {
encoding: 'utf8',
})
const userTsConfig = CommentJson.parse(userTsConfigContent) as {
compilerOptions?: CompilerOptions
}
if (!userTsConfig.compilerOptions && !('extends' in userTsConfig)) {
userTsConfig.compilerOptions = {}
}
if (!userTsConfig.compilerOptions.paths?.['@payload-config']) {
userTsConfig.compilerOptions.paths = {
...(userTsConfig.compilerOptions.paths || {}),
'@payload-config': ['./payload.config.ts'],
}
await fse.writeFile(tsConfigPath, CommentJson.stringify(userTsConfig, null, 2))
}
}
async function applyPayloadTemplateFiles(args: InitNextArgs): Promise<InitNextResult> {
const { '--debug': debug, projectDir, useDistFiles } = args
export async function initNext(
args: Pick<CliArgs, '--debug'> & { nextDir?: string; useDistFiles?: boolean },
): Promise<{ success: boolean }> {
const { '--debug': debug, nextDir, useDistFiles } = args
info('Initializing Payload app in Next.js project', 1)
@@ -90,18 +18,24 @@ async function applyPayloadTemplateFiles(args: InitNextArgs): Promise<InitNextRe
if (debug) origDebug(message)
}
if (!fs.existsSync(projectDir)) {
return { reason: `Could not find specified project directory at ${projectDir}`, success: false }
let projectDir = process.cwd()
if (nextDir) {
projectDir = path.resolve(projectDir, nextDir)
if (debug) logDebug(`Overriding project directory to ${projectDir}`)
}
if (!fs.existsSync(projectDir)) {
error(`Could not find specified project directory at ${projectDir}`)
return { success: false }
}
// Next.js configs can be next.config.js, next.config.mjs, etc.
const foundConfig = (await globby('next.config.*js', { cwd: projectDir }))?.[0]
const nextConfigPath = path.resolve(projectDir, foundConfig)
if (!fs.existsSync(nextConfigPath)) {
return {
reason: `No next.config.js found at ${nextConfigPath}. Ensure you are in a Next.js project directory.`,
success: false,
}
error(
`No next.config.js found at ${nextConfigPath}. Ensure you are in a Next.js project directory.`,
)
return { success: false }
} else {
if (debug) logDebug(`Found Next config at ${nextConfigPath}`)
}
@@ -109,27 +43,21 @@ async function applyPayloadTemplateFiles(args: InitNextArgs): Promise<InitNextRe
const templateFilesPath =
__dirname.endsWith('dist') || useDistFiles
? path.resolve(__dirname, '../..', 'dist/app')
: path.resolve(__dirname, '../../../../app')
: path.resolve(__dirname, '../../../next/src/app')
if (debug) logDebug(`Using template files from: ${templateFilesPath}`)
if (!fs.existsSync(templateFilesPath)) {
return {
reason: `Could not find template source files from ${templateFilesPath}`,
success: false,
}
error(`Could not find template source files from ${templateFilesPath}`)
return { success: false }
} else {
if (debug) logDebug('Found template source files')
}
// src/app or app
const userAppDirGlob = await globby(['**/app'], {
cwd: projectDir,
onlyDirectories: true,
})
const userAppDir = path.resolve(projectDir, userAppDirGlob?.[0])
const userAppDir = path.resolve(projectDir, 'src/app')
if (!fs.existsSync(userAppDir)) {
return { reason: `Could not find user app directory inside ${projectDir}`, success: false }
error(`Could not find user app directory at ${userAppDir}`)
return { success: false }
} else {
logDebug(`Found user app directory: ${userAppDir}`)
}
@@ -137,83 +65,5 @@ async function applyPayloadTemplateFiles(args: InitNextArgs): Promise<InitNextRe
logDebug(`Copying template files from ${templateFilesPath} to ${userAppDir}`)
copyRecursiveSync(templateFilesPath, userAppDir, debug)
success('Successfully initialized.')
return { success: true, userAppDir }
}
async function installDeps(projectDir: string) {
const packageManager = await detect({ cwd: projectDir })
if (!packageManager) {
throw new Error('Could not detect package manager')
}
info(`Installing dependencies with ${packageManager}`, 1)
const packagesToInstall = [
'payload',
'@payloadcms/db-mongodb',
'@payloadcms/next',
'@payloadcms/richtext-slate',
'@payloadcms/ui',
].map((pkg) => `${pkg}@alpha`)
let exitCode = 0
switch (packageManager) {
case 'npm': {
;({ exitCode } = await execa('npm', ['install', '--save', ...packagesToInstall], {
cwd: projectDir,
}))
break
}
case 'yarn':
case 'pnpm': {
;({ exitCode } = await execa(packageManager, ['add', ...packagesToInstall], {
cwd: projectDir,
}))
break
}
case 'bun': {
warning('Bun support is untested.')
;({ exitCode } = await execa('bun', ['add', ...packagesToInstall], { cwd: projectDir }))
break
}
}
if (exitCode !== 0) {
error(`Failed to install dependencies with ${packageManager}`)
} else {
success(`Successfully installed dependencies`)
}
return { success: exitCode === 0 }
}
function findOrCreatePayloadConfig(projectDir: string) {
const configPath = path.resolve(projectDir, 'payload.config.ts')
if (fs.existsSync(configPath)) {
return { message: 'Found existing payload.config.ts', success: true }
} else {
// Create default config
// TODO: Pull this from templates
const defaultConfig = `import path from "path";
import { mongooseAdapter } from "@payloadcms/db-mongodb"; // database-adapter-import
import { slateEditor } from "@payloadcms/richtext-slate"; // editor-import
import { buildConfig } from "payload/config";
export default buildConfig({
editor: slateEditor({}), // editor-config
collections: [],
secret: "asdfasdf",
typescript: {
outputFile: path.resolve(__dirname, "payload-types.ts"),
},
graphQL: {
schemaOutputFile: path.resolve(__dirname, "generated-schema.graphql"),
},
db: mongooseAdapter({
url: "mongodb://localhost:27017/next-payload-3",
}),
});
`
fse.writeFileSync(configPath, defaultConfig)
return { message: 'Created default payload.config.ts', success: true }
}
return { success: true }
}

View File

@@ -12,7 +12,7 @@ import { parseTemplate } from './lib/parse-template'
import { selectDb } from './lib/select-db'
import { getValidTemplates, validateTemplate } from './lib/templates'
import { writeEnvFile } from './lib/write-env-file'
import { error, success } from './utils/log'
import { success } from './utils/log'
import { helpMessage, successMessage, welcomeMessage } from './utils/messages'
export class Main {
@@ -61,11 +61,6 @@ export class Main {
if (this.args['--init-next']) {
const result = await initNext(this.args)
if (!result.success) {
error(result.reason || 'Failed to initialize Payload app in Next.js project')
} else {
success('Payload app successfully initialized in Next.js project')
}
process.exit(result.success ? 0 : 1)
}

View File

@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": true,
"sourceMaps": "inline",
"jsc": {
"target": "esnext",
"parser": {
@@ -10,6 +10,6 @@
}
},
"module": {
"type": "es6"
"type": "commonjs"
}
}

View File

@@ -1,11 +1,10 @@
{
"name": "@payloadcms/db-mongodb",
"version": "3.0.0-alpha.42",
"version": "3.0.0-alpha.10",
"description": "The officially supported MongoDB database adapter for Payload - Update 2",
"repository": "https://github.com/payloadcms/payload",
"license": "MIT",
"homepage": "https://payloadcms.com",
"type": "module",
"author": {
"email": "info@payloadcms.com",
"name": "Payload",

View File

@@ -4,16 +4,9 @@ import type { Connect } from 'payload/database'
import mongoose from 'mongoose'
import type { MongooseAdapter } from './index.js'
export const connect: Connect = async function connect(
this: MongooseAdapter,
options = {
hotReload: false,
},
) {
const { hotReload } = options
import type { MongooseAdapter } from '.'
export const connect: Connect = async function connect(this: MongooseAdapter) {
if (this.url === false) {
return
}
@@ -23,6 +16,7 @@ export const connect: Connect = async function connect(
}
const urlToConnect = this.url
const successfulConnectionMessage = 'Connected to MongoDB server successfully!'
const connectionOptions: ConnectOptions & { useFacet: undefined } = {
autoIndex: true,
@@ -30,8 +24,6 @@ export const connect: Connect = async function connect(
useFacet: undefined,
}
if (hotReload) connectionOptions.autoIndex = false
try {
this.connection = (await mongoose.connect(urlToConnect, connectionOptions)).connection
@@ -42,13 +34,12 @@ export const connect: Connect = async function connect(
this.beginTransaction = undefined
}
if (!hotReload) {
if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
this.payload.logger.info('---- DROPPING DATABASE ----')
await mongoose.connection.dropDatabase()
this.payload.logger.info('---- DROPPED DATABASE ----')
}
if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
this.payload.logger.info('---- DROPPING DATABASE ----')
await mongoose.connection.dropDatabase()
this.payload.logger.info('---- DROPPED DATABASE ----')
}
this.payload.logger.info(successfulConnectionMessage)
} catch (err) {
this.payload.logger.error(`Error: cannot connect to MongoDB. Details: ${err.message}`, err)
process.exit(1)

View File

@@ -1,10 +1,10 @@
import type { Create } from 'payload/database'
import type { Document, PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import handleError from './utilities/handleError.js'
import { withSession } from './withSession.js'
import handleError from './utilities/handleError'
import { withSession } from './withSession'
export const create: Create = async function create(
this: MongooseAdapter,

View File

@@ -1,14 +1,14 @@
import type { CreateGlobal } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const createGlobal: CreateGlobal = async function createGlobal(
this: MongooseAdapter,
{ slug, data, req = {} as PayloadRequest },
{ data, req = {} as PayloadRequest, slug },
) {
const Model = this.globals
const global = {

View File

@@ -2,9 +2,9 @@ import type { CreateGlobalVersion } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { withSession } from './withSession.js'
import { withSession } from './withSession'
export const createGlobalVersion: CreateGlobalVersion = async function createGlobalVersion(
this: MongooseAdapter,

View File

@@ -3,7 +3,6 @@ import type { CreateMigration } from 'payload/database'
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
const migrationTemplate = (upSQL?: string, downSQL?: string) => `import {
MigrateUpArgs,
@@ -24,9 +23,6 @@ export const createMigration: CreateMigration = async function createMigration({
migrationName,
payload,
}) {
const filename = fileURLToPath(import.meta.url)
const dirname = path.dirname(filename)
const dir = payload.db.migrationDir
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
@@ -41,11 +37,11 @@ export const createMigration: CreateMigration = async function createMigration({
const predefinedMigrationName = file.replace('@payloadcms/db-mongodb/', '')
migrationName = predefinedMigrationName
const cleanPath = path.join(dirname, `../predefinedMigrations/${predefinedMigrationName}.js`)
const cleanPath = path.join(__dirname, `../predefinedMigrations/${predefinedMigrationName}.js`)
// Check if predefined migration exists
if (fs.existsSync(cleanPath)) {
const { down, up } = await eval(`import(${cleanPath})`)
const { down, up } = eval(`require(${cleanPath})`)
migrationFileContent = migrationTemplate(up, down)
} else {
payload.logger.error({

View File

@@ -2,9 +2,9 @@ import type { CreateVersion } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { withSession } from './withSession.js'
import { withSession } from './withSession'
export const createVersion: CreateVersion = async function createVersion(
this: MongooseAdapter,

View File

@@ -1,9 +1,9 @@
import type { DeleteMany } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { withSession } from './withSession.js'
import { withSession } from './withSession'
export const deleteMany: DeleteMany = async function deleteMany(
this: MongooseAdapter,

View File

@@ -2,10 +2,10 @@ import type { DeleteOne } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const deleteOne: DeleteOne = async function deleteOne(
this: MongooseAdapter,

View File

@@ -1,9 +1,9 @@
import type { DeleteVersions } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { withSession } from './withSession.js'
import { withSession } from './withSession'
export const deleteVersions: DeleteVersions = async function deleteVersions(
this: MongooseAdapter,

View File

@@ -2,7 +2,7 @@ import type { Destroy } from 'payload/database'
import mongoose from 'mongoose'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from './index'
export const destroy: Destroy = async function destroy(this: MongooseAdapter) {
if (this.mongoMemoryServer) {
@@ -10,7 +10,6 @@ export const destroy: Destroy = async function destroy(this: MongooseAdapter) {
await mongoose.connection.close()
await this.mongoMemoryServer.stop()
} else {
await mongoose.disconnect()
await mongoose.connection.close()
}
Object.keys(mongoose.models).map((model) => mongoose.deleteModel(model))
}

View File

@@ -4,11 +4,11 @@ import type { PayloadRequest } from 'payload/types'
import { flattenWhereToOperators } from 'payload/database'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { buildSortParam } from './queries/buildSortParam.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import { buildSortParam } from './queries/buildSortParam'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const find: Find = async function find(
this: MongooseAdapter,

View File

@@ -3,10 +3,10 @@ import type { PayloadRequest } from 'payload/types'
import { combineQueries } from 'payload/database'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const findGlobal: FindGlobal = async function findGlobal(
this: MongooseAdapter,

View File

@@ -5,11 +5,11 @@ import type { PayloadRequest } from 'payload/types'
import { flattenWhereToOperators } from 'payload/database'
import { buildVersionGlobalFields } from 'payload/versions'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { buildSortParam } from './queries/buildSortParam.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import { buildSortParam } from './queries/buildSortParam'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const findGlobalVersions: FindGlobalVersions = async function findGlobalVersions(
this: MongooseAdapter,

View File

@@ -3,10 +3,10 @@ import type { FindOne } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { Document } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const findOne: FindOne = async function findOne(
this: MongooseAdapter,

View File

@@ -4,11 +4,11 @@ import type { PayloadRequest } from 'payload/types'
import { flattenWhereToOperators } from 'payload/database'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { buildSortParam } from './queries/buildSortParam.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import { buildSortParam } from './queries/buildSortParam'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const findVersions: FindVersions = async function findVersions(
this: MongooseAdapter,

View File

@@ -8,35 +8,35 @@ import mongoose from 'mongoose'
import path from 'path'
import { createDatabaseAdapter } from 'payload/database'
import type { CollectionModel, GlobalModel } from './types.js'
import type { CollectionModel, GlobalModel } from './types'
import { connect } from './connect.js'
import { create } from './create.js'
import { createGlobal } from './createGlobal.js'
import { createGlobalVersion } from './createGlobalVersion.js'
import { createMigration } from './createMigration.js'
import { createVersion } from './createVersion.js'
import { deleteMany } from './deleteMany.js'
import { deleteOne } from './deleteOne.js'
import { deleteVersions } from './deleteVersions.js'
import { destroy } from './destroy.js'
import { find } from './find.js'
import { findGlobal } from './findGlobal.js'
import { findGlobalVersions } from './findGlobalVersions.js'
import { findOne } from './findOne.js'
import { findVersions } from './findVersions.js'
import { init } from './init.js'
import { migrateFresh } from './migrateFresh.js'
import { queryDrafts } from './queryDrafts.js'
import { beginTransaction } from './transactions/beginTransaction.js'
import { commitTransaction } from './transactions/commitTransaction.js'
import { rollbackTransaction } from './transactions/rollbackTransaction.js'
import { updateGlobal } from './updateGlobal.js'
import { updateGlobalVersion } from './updateGlobalVersion.js'
import { updateOne } from './updateOne.js'
import { updateVersion } from './updateVersion.js'
import { connect } from './connect'
import { create } from './create'
import { createGlobal } from './createGlobal'
import { createGlobalVersion } from './createGlobalVersion'
import { createMigration } from './createMigration'
import { createVersion } from './createVersion'
import { deleteMany } from './deleteMany'
import { deleteOne } from './deleteOne'
import { deleteVersions } from './deleteVersions'
import { destroy } from './destroy'
import { find } from './find'
import { findGlobal } from './findGlobal'
import { findGlobalVersions } from './findGlobalVersions'
import { findOne } from './findOne'
import { findVersions } from './findVersions'
import { init } from './init'
import { migrateFresh } from './migrateFresh'
import { queryDrafts } from './queryDrafts'
import { beginTransaction } from './transactions/beginTransaction'
import { commitTransaction } from './transactions/commitTransaction'
import { rollbackTransaction } from './transactions/rollbackTransaction'
import { updateGlobal } from './updateGlobal'
import { updateGlobalVersion } from './updateGlobalVersion'
import { updateOne } from './updateOne'
import { updateVersion } from './updateVersion'
export type { MigrateDownArgs, MigrateUpArgs } from './types.js'
export type { MigrateDownArgs, MigrateUpArgs } from './types'
import type { DatabaseAdapterObj } from 'payload/database'
export interface Args {

View File

@@ -11,15 +11,15 @@ import {
getVersionsModelName,
} from 'payload/versions'
import type { MongooseAdapter } from './index.js'
import type { CollectionModel } from './types.js'
import type { MongooseAdapter } from '.'
import type { CollectionModel } from './types'
import buildCollectionSchema from './models/buildCollectionSchema.js'
import { buildGlobalModel } from './models/buildGlobalModel.js'
import buildSchema from './models/buildSchema.js'
import getBuildQueryPlugin from './queries/buildQuery.js'
import buildCollectionSchema from './models/buildCollectionSchema'
import { buildGlobalModel } from './models/buildGlobalModel'
import buildSchema from './models/buildSchema'
import getBuildQueryPlugin from './queries/buildQuery'
export const init: Init = function init(this: MongooseAdapter) {
export const init: Init = async function init(this: MongooseAdapter) {
this.payload.config.collections.forEach((collection: SanitizedCollectionConfig) => {
const schema = buildCollectionSchema(collection, this.payload.config)

View File

@@ -8,7 +8,7 @@ import {
} from 'payload/database'
import prompts from 'prompts'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
/**
* Drop the current database and run all migrate up functions

View File

@@ -4,8 +4,8 @@ import type { SanitizedCollectionConfig } from 'payload/types'
import paginate from 'mongoose-paginate-v2'
import getBuildQueryPlugin from '../queries/buildQuery.js'
import buildSchema from './buildSchema.js'
import getBuildQueryPlugin from '../queries/buildQuery'
import buildSchema from './buildSchema'
const buildCollectionSchema = (
collection: SanitizedCollectionConfig,

View File

@@ -2,10 +2,10 @@ import type { SanitizedConfig } from 'payload/config'
import mongoose from 'mongoose'
import type { GlobalModel } from '../types.js'
import type { GlobalModel } from '../types'
import getBuildQueryPlugin from '../queries/buildQuery.js'
import buildSchema from './buildSchema.js'
import getBuildQueryPlugin from '../queries/buildQuery'
import buildSchema from './buildSchema'
export const buildGlobalModel = (config: SanitizedConfig): GlobalModel | null => {
if (config.globals && config.globals.length > 0) {

View File

@@ -1,7 +1,8 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
/* eslint-disable class-methods-use-this */
/* eslint-disable @typescript-eslint/no-use-before-define */
import type { IndexOptions, Schema, SchemaOptions, SchemaTypeOptions } from 'mongoose'
/* eslint-disable no-use-before-define */
import type { IndexOptions, SchemaOptions, SchemaTypeOptions } from 'mongoose'
import type { SanitizedConfig, SanitizedLocalizationConfig } from 'payload/config'
import type {
ArrayField,
@@ -31,7 +32,7 @@ import type {
UploadField,
} from 'payload/types'
import mongoose from 'mongoose'
import { Schema } from 'mongoose'
import {
fieldAffectsData,
fieldIsLocalized,
@@ -125,7 +126,7 @@ const buildSchema = (
}
}
const schema = new mongoose.Schema(fields, options)
const schema = new Schema(fields, options)
schemaFields.forEach((field) => {
if (!fieldIsPresentationalOnly(field)) {
@@ -175,7 +176,7 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
buildSchemaOptions: BuildSchemaOptions,
): void => {
const fieldSchema = {
type: [new mongoose.Schema({}, { _id: false, discriminatorKey: 'blockType' })],
type: [new Schema({}, { _id: false, discriminatorKey: 'blockType' })],
default: undefined,
}
@@ -184,7 +185,7 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
})
field.blocks.forEach((blockItem: Block) => {
const blockSchema = new mongoose.Schema({}, { _id: false, id: false })
const blockSchema = new Schema({}, { _id: false, id: false })
blockItem.fields.forEach((blockField) => {
const addFieldSchema: FieldSchemaGenerator = fieldToSchemaMap[blockField.type]
@@ -306,10 +307,7 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
config: SanitizedConfig,
buildSchemaOptions: BuildSchemaOptions,
): void => {
const baseSchema = {
...formatBaseSchema(field, buildSchemaOptions),
type: mongoose.Schema.Types.Mixed,
}
const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Schema.Types.Mixed }
schema.add({
[field.name]: localizeSchema(field, baseSchema, config.localization),
@@ -407,17 +405,17 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
localeSchema = {
...formatBaseSchema(field, buildSchemaOptions),
_id: false,
type: mongoose.Schema.Types.Mixed,
type: Schema.Types.Mixed,
relationTo: { type: String, enum: field.relationTo },
value: {
type: mongoose.Schema.Types.Mixed,
type: Schema.Types.Mixed,
refPath: `${field.name}.${locale}.relationTo`,
},
}
} else {
localeSchema = {
...formatBaseSchema(field, buildSchemaOptions),
type: mongoose.Schema.Types.Mixed,
type: Schema.Types.Mixed,
ref: field.relationTo,
}
}
@@ -433,10 +431,10 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
schemaToReturn = {
...formatBaseSchema(field, buildSchemaOptions),
_id: false,
type: mongoose.Schema.Types.Mixed,
type: Schema.Types.Mixed,
relationTo: { type: String, enum: field.relationTo },
value: {
type: mongoose.Schema.Types.Mixed,
type: Schema.Types.Mixed,
refPath: `${field.name}.relationTo`,
},
}
@@ -450,7 +448,7 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
} else {
schemaToReturn = {
...formatBaseSchema(field, buildSchemaOptions),
type: mongoose.Schema.Types.Mixed,
type: Schema.Types.Mixed,
ref: field.relationTo,
}
@@ -472,10 +470,7 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
config: SanitizedConfig,
buildSchemaOptions: BuildSchemaOptions,
): void => {
const baseSchema = {
...formatBaseSchema(field, buildSchemaOptions),
type: mongoose.Schema.Types.Mixed,
}
const baseSchema = { ...formatBaseSchema(field, buildSchemaOptions), type: Schema.Types.Mixed }
schema.add({
[field.name]: localizeSchema(field, baseSchema, config.localization),
@@ -591,7 +586,7 @@ const fieldToSchemaMap: Record<string, FieldSchemaGenerator> = {
): void => {
const baseSchema = {
...formatBaseSchema(field, buildSchemaOptions),
type: mongoose.Schema.Types.Mixed,
type: Schema.Types.Mixed,
ref: field.relationTo,
}

View File

@@ -1,7 +1,7 @@
import type { Payload } from 'payload'
import type { Field, Where } from 'payload/types'
import { parseParams } from './parseParams.js'
import { parseParams } from './parseParams'
export async function buildAndOrConditions({
collectionSlug,

View File

@@ -3,7 +3,7 @@ import type { Field, Where } from 'payload/types'
import { QueryError } from 'payload/errors'
import { parseParams } from './parseParams.js'
import { parseParams } from './parseParams'
type GetBuildQueryPluginArgs = {
collectionSlug?: string

View File

@@ -3,19 +3,16 @@ import type { PathToQuery } from 'payload/database'
import type { Field } from 'payload/types'
import type { Operator } from 'payload/types'
import ObjectIdImport from 'bson-objectid'
import ObjectId from 'bson-objectid'
import mongoose from 'mongoose'
import { getLocalizedPaths } from 'payload/database'
import { fieldAffectsData } from 'payload/types'
import { validOperators } from 'payload/types'
import type { MongooseAdapter } from '../index.js'
import type { MongooseAdapter } from '..'
import { operatorMap } from './operatorMap.js'
import { sanitizeQueryValue } from './sanitizeQueryValue.js'
const ObjectId = (ObjectIdImport.default ||
ObjectIdImport) as unknown as typeof ObjectIdImport.default
import { operatorMap } from './operatorMap'
import { sanitizeQueryValue } from './sanitizeQueryValue'
type SearchParam = {
path?: string
@@ -207,9 +204,7 @@ export async function buildSearchParam({
if (typeof formattedValue === 'string') {
if (mongoose.Types.ObjectId.isValid(formattedValue)) {
result.value.$or.push({
[path]: { [operatorKey]: new ObjectId(formattedValue) },
})
result.value.$or.push({ [path]: { [operatorKey]: new ObjectId(formattedValue) } })
} else {
;(Array.isArray(field.relationTo) ? field.relationTo : [field.relationTo]).forEach(
(relationTo) => {

View File

@@ -2,7 +2,7 @@ import type { PaginateOptions } from 'mongoose'
import type { SanitizedConfig } from 'payload/config'
import type { Field } from 'payload/types'
import { getLocalizedSortProperty } from './getLocalizedSortProperty.js'
import { getLocalizedSortProperty } from './getLocalizedSortProperty'
type Args = {
config: SanitizedConfig

View File

@@ -1,6 +1,6 @@
import { sanitizeConfig } from 'payload/config'
import { Config } from 'payload/config'
import { getLocalizedSortProperty } from './getLocalizedSortProperty.js'
import { getLocalizedSortProperty } from './getLocalizedSortProperty'
const config = {
localization: {

View File

@@ -9,8 +9,8 @@ import deepmerge from 'deepmerge'
import { validOperators } from 'payload/types'
import { combineMerge } from 'payload/utilities'
import { buildAndOrConditions } from './buildAndOrConditions.js'
import { buildSearchParam } from './buildSearchParams.js'
import { buildAndOrConditions } from './buildAndOrConditions'
import { buildSearchParam } from './buildSearchParams'
export async function parseParams({
collectionSlug,

View File

@@ -4,11 +4,11 @@ import type { PayloadRequest } from 'payload/types'
import { combineQueries, flattenWhereToOperators } from 'payload/database'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { buildSortParam } from './queries/buildSortParam.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import { buildSortParam } from './queries/buildSortParam'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const queryDrafts: QueryDrafts = async function queryDrafts(
this: MongooseAdapter,

View File

@@ -4,7 +4,7 @@ import type { BeginTransaction } from 'payload/database'
import { APIError } from 'payload/errors'
import { v4 as uuid } from 'uuid'
import type { MongooseAdapter } from '../index.js'
import type { MongooseAdapter } from '../index'
export const beginTransaction: BeginTransaction = async function beginTransaction(
this: MongooseAdapter,

View File

@@ -25,7 +25,7 @@ import type {
UploadField,
} from 'payload/types'
import type { BuildQueryArgs } from './queries/buildQuery.js'
import type { BuildQueryArgs } from './queries/buildQuery'
export interface CollectionModel extends Model<any>, PaginateModel<any> {
/** buildQuery is used to transform payload's where operator into what can be used by mongoose (e.g. id => _id) */

View File

@@ -1,10 +1,10 @@
import type { UpdateGlobal } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const updateGlobal: UpdateGlobal = async function updateGlobal(
this: MongooseAdapter,

View File

@@ -1,9 +1,9 @@
import type { UpdateGlobalVersionArgs } from 'payload/database'
import type { PayloadRequest, TypeWithID } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { withSession } from './withSession.js'
import { withSession } from './withSession'
export async function updateGlobalVersion<T extends TypeWithID>(
this: MongooseAdapter,

View File

@@ -1,11 +1,11 @@
import type { UpdateOne } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import handleError from './utilities/handleError.js'
import sanitizeInternalFields from './utilities/sanitizeInternalFields.js'
import { withSession } from './withSession.js'
import handleError from './utilities/handleError'
import sanitizeInternalFields from './utilities/sanitizeInternalFields'
import { withSession } from './withSession'
export const updateOne: UpdateOne = async function updateOne(
this: MongooseAdapter,

View File

@@ -1,9 +1,9 @@
import type { UpdateVersion } from 'payload/database'
import type { PayloadRequest } from 'payload/types'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from '.'
import { withSession } from './withSession.js'
import { withSession } from './withSession'
export const updateVersion: UpdateVersion = async function updateVersion(
this: MongooseAdapter,

View File

@@ -1,6 +1,6 @@
import type { ClientSession } from 'mongoose'
import type { MongooseAdapter } from './index.js'
import type { MongooseAdapter } from './index'
/**
* returns the session belonging to the transaction of the req.session if exists

View File

@@ -1,6 +1,6 @@
{
"$schema": "https://json.schemastore.org/swcrc",
"sourceMaps": true,
"sourceMaps": "inline",
"jsc": {
"target": "esnext",
"parser": {
@@ -10,6 +10,6 @@
}
},
"module": {
"type": "es6"
"type": "commonjs"
}
}

View File

@@ -1,11 +1,10 @@
{
"name": "@payloadcms/db-postgres",
"version": "3.0.0-alpha.42",
"version": "0.7.0",
"description": "The officially supported Postgres database adapter for Payload",
"repository": "https://github.com/payloadcms/payload",
"license": "MIT",
"homepage": "https://payloadcms.com",
"type": "module",
"author": {
"email": "info@payloadcms.com",
"name": "Payload",

View File

@@ -1,13 +1,13 @@
import type { Payload } from 'payload'
import type { Connect } from 'payload/database'
import { sql } from 'drizzle-orm'
import { eq, sql } from 'drizzle-orm'
import { drizzle } from 'drizzle-orm/node-postgres'
import pg from 'pg'
import { numeric, timestamp, varchar } from 'drizzle-orm/pg-core'
import { Pool } from 'pg'
import prompts from 'prompts'
import type { PostgresAdapter } from './types.js'
import { pushDevSchema } from './utilities/pushDevSchema.js'
import type { PostgresAdapter } from './types'
const connectWithReconnect = async function ({
adapter,
@@ -46,14 +46,7 @@ const connectWithReconnect = async function ({
})
}
export const connect: Connect = async function connect(
this: PostgresAdapter,
options = {
hotReload: false,
},
) {
const { hotReload } = options
export const connect: Connect = async function connect(this: PostgresAdapter, payload) {
this.schema = {
...this.tables,
...this.relations,
@@ -61,27 +54,24 @@ export const connect: Connect = async function connect(
}
try {
this.pool = new pg.Pool(this.poolOptions)
await connectWithReconnect({ adapter: this, payload: this.payload })
this.pool = new Pool(this.poolOptions)
await connectWithReconnect({ adapter: this, payload })
const logger = this.logger || false
this.drizzle = drizzle(this.pool, { logger, schema: this.schema })
if (!hotReload) {
if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
this.payload.logger.info(`---- DROPPING TABLES SCHEMA(${this.schemaName || 'public'}) ----`)
await this.drizzle.execute(
sql.raw(`
drop schema if exists ${this.schemaName || 'public'} cascade;
create schema ${this.schemaName || 'public'};
`),
)
this.payload.logger.info('---- DROPPED TABLES ----')
}
if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
this.payload.logger.info(`---- DROPPING TABLES SCHEMA(${this.schemaName || 'public'}) ----`)
await this.drizzle.execute(
sql.raw(`
drop schema if exists ${this.schemaName || 'public'} cascade;
create schema ${this.schemaName || 'public'};
`),
)
this.payload.logger.info('---- DROPPED TABLES ----')
}
} catch (err) {
this.payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err)
payload.logger.error(`Error: cannot connect to Postgres. Details: ${err.message}`, err)
process.exit(1)
}
@@ -93,5 +83,70 @@ export const connect: Connect = async function connect(
)
return
await pushDevSchema(this)
const { pushSchema } = require('drizzle-kit/payload')
// This will prompt if clarifications are needed for Drizzle to push new schema
const { apply, hasDataLoss, statementsToExecute, warnings } = await pushSchema(
this.schema,
this.drizzle,
)
if (warnings.length) {
let message = `Warnings detected during schema push: \n\n${warnings.join('\n')}\n\n`
if (hasDataLoss) {
message += `DATA LOSS WARNING: Possible data loss detected if schema is pushed.\n\n`
}
message += `Accept warnings and push schema to database?`
const { confirm: acceptWarnings } = await prompts(
{
name: 'confirm',
type: 'confirm',
initial: false,
message,
},
{
onCancel: () => {
process.exit(0)
},
},
)
// Exit if user does not accept warnings.
// Q: Is this the right type of exit for this interaction?
if (!acceptWarnings) {
process.exit(0)
}
}
await apply()
// Migration table def in order to use query using drizzle
const migrationsSchema = this.pgSchema.table('payload_migrations', {
name: varchar('name'),
batch: numeric('batch'),
created_at: timestamp('created_at'),
updated_at: timestamp('updated_at'),
})
const devPush = await this.drizzle
.select()
.from(migrationsSchema)
.where(eq(migrationsSchema.batch, '-1'))
if (!devPush.length) {
await this.drizzle.insert(migrationsSchema).values({
name: 'dev',
batch: '-1',
})
} else {
await this.drizzle
.update(migrationsSchema)
.set({
updated_at: new Date(),
})
.where(eq(migrationsSchema.batch, '-1'))
}
}

View File

@@ -2,9 +2,9 @@ import type { Create } from 'payload/database'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow/index.js'
import { upsertRow } from './upsertRow'
export const create: Create = async function create(
this: PostgresAdapter,

View File

@@ -3,9 +3,9 @@ import type { PayloadRequest, TypeWithID } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow/index.js'
import { upsertRow } from './upsertRow'
export async function createGlobal<T extends TypeWithID>(
this: PostgresAdapter,

View File

@@ -6,9 +6,9 @@ import { sql } from 'drizzle-orm'
import { buildVersionGlobalFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow/index.js'
import { upsertRow } from './upsertRow'
export async function createGlobalVersion<T extends TypeWithID>(
this: PostgresAdapter,

View File

@@ -5,7 +5,7 @@ import type { CreateMigration } from 'payload/database'
import fs from 'fs'
import prompts from 'prompts'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
const migrationTemplate = (
upSQL?: string,
@@ -60,7 +60,7 @@ export const createMigration: CreateMigration = async function createMigration(
fs.mkdirSync(dir)
}
const { generateDrizzleJson, generateMigration } = await import('drizzle-kit/payload')
const { generateDrizzleJson, generateMigration } = require('drizzle-kit/payload')
const [yyymmdd, hhmmss] = new Date().toISOString().split('T')
const formattedDate = yyymmdd.replace(/\D/g, '')

View File

@@ -5,9 +5,9 @@ import { sql } from 'drizzle-orm'
import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { upsertRow } from './upsertRow/index.js'
import { upsertRow } from './upsertRow'
export async function createVersion<T extends TypeWithID>(
this: PostgresAdapter,

View File

@@ -4,9 +4,9 @@ import type { PayloadRequest } from 'payload/types'
import { inArray } from 'drizzle-orm'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany.js'
import { findMany } from './find/findMany'
export const deleteMany: DeleteMany = async function deleteMany(
this: PostgresAdapter,

View File

@@ -3,11 +3,11 @@ import type { PayloadRequest } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { buildFindManyArgs } from './find/buildFindManyArgs.js'
import buildQuery from './queries/buildQuery.js'
import { transform } from './transform/read/index.js'
import { buildFindManyArgs } from './find/buildFindManyArgs'
import buildQuery from './queries/buildQuery'
import { transform } from './transform/read'
export const deleteOne: DeleteOne = async function deleteOne(
this: PostgresAdapter,

View File

@@ -5,9 +5,9 @@ import { inArray } from 'drizzle-orm'
import { buildVersionCollectionFields } from 'payload/versions'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany.js'
import { findMany } from './find/findMany'
export const deleteVersions: DeleteVersions = async function deleteVersion(
this: PostgresAdapter,

View File

@@ -1,14 +1,8 @@
import type { Destroy } from 'payload/database'
import type { PostgresAdapter } from './types.js'
import { pushDevSchema } from './utilities/pushDevSchema.js'
import type { PostgresAdapter } from './types'
export const destroy: Destroy = async function destroy(this: PostgresAdapter) {
if (process.env.NODE_ENV !== 'production') {
await pushDevSchema(this)
} else {
// TODO: this hangs test suite for some reason
// await this.pool.end()
}
// TODO: this hangs test suite for some reason
// await this.pool.end()
}

View File

@@ -3,9 +3,9 @@ import type { PayloadRequest, SanitizedCollectionConfig } from 'payload/types'
import toSnakeCase from 'to-snake-case'
import type { PostgresAdapter } from './types.js'
import type { PostgresAdapter } from './types'
import { findMany } from './find/findMany.js'
import { findMany } from './find/findMany'
export const find: Find = async function find(
this: PostgresAdapter,

View File

@@ -1,9 +1,9 @@
import type { DBQueryConfig } from 'drizzle-orm'
import type { Field } from 'payload/types'
import type { PostgresAdapter } from '../types.js'
import type { PostgresAdapter } from '../types'
import { traverseFields } from './traverseFields.js'
import { traverseFields } from './traverseFields'
type BuildFindQueryArgs = {
adapter: PostgresAdapter

Some files were not shown because too many files have changed in this diff Show More