Skip to content

Commit

Permalink
breaking: move shared HTTP utils to the framework (#9402)
Browse files Browse the repository at this point in the history
Fixes: FRMW-2728, FRMW-2729

After this PR gets merged the following middleware will be exported from the `@medusajs/framework/http` import path.

- applyParamsAsFilters
- clearFiltersByKey
- applyDefaultFilters
- setContext
- getQueryConfig
- httpCompression
- maybeApplyLinkFilter
- refetchEntities
- unlessPath
- validateBody
- validateQuery

Co-authored-by: Adrien de Peretti <[email protected]>
  • Loading branch information
thetutlage and adrien2p authored Oct 3, 2024
1 parent 193f934 commit 48e0016
Show file tree
Hide file tree
Showing 557 changed files with 2,368 additions and 3,502 deletions.
5 changes: 4 additions & 1 deletion packages/cli/create-medusa-app/src/commands/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ import {
installNextjsStarter,
startNextjsStarter,
} from "../utils/nextjs-utils.js"
import { getNodeVersion, MIN_SUPPORTED_NODE_VERSION } from "../utils/node-version.js"
import {
getNodeVersion,
MIN_SUPPORTED_NODE_VERSION,
} from "../utils/node-version.js"

const slugify = slugifyType.default

Expand Down
26 changes: 18 additions & 8 deletions packages/cli/create-medusa-app/src/utils/create-db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { EOL } from "os"
import pg from "pg"
import postgresClient, { DEFAULT_HOST, DEFAULT_PORT } from "./postgres-client.js"
import postgresClient, {
DEFAULT_HOST,
DEFAULT_PORT,
} from "./postgres-client.js"
import inquirer from "inquirer"
import logMessage from "./log-message.js"
import formatConnectionString from "./format-connection-string.js"
Expand All @@ -16,8 +19,13 @@ export default async function createDb({ client, db }: CreateDbOptions) {
await client.query(`CREATE DATABASE "${db}"`)
}

async function doesDbExist (client: pg.Client, dbName: string): Promise<boolean> {
const result = await client.query(`SELECT datname FROM pg_catalog.pg_database WHERE datname='${dbName}';`)
async function doesDbExist(
client: pg.Client,
dbName: string
): Promise<boolean> {
const result = await client.query(
`SELECT datname FROM pg_catalog.pg_database WHERE datname='${dbName}';`
)

return !!result.rowCount
}
Expand Down Expand Up @@ -75,14 +83,14 @@ async function getForDbName({

const defaultConnectionOptions = {
host: DEFAULT_HOST,
port: DEFAULT_PORT
port: DEFAULT_PORT,
}

try {
client = await postgresClient({
user: postgresUsername,
password: postgresPassword,
...defaultConnectionOptions
...defaultConnectionOptions,
})
} catch (e) {
if (verbose) {
Expand Down Expand Up @@ -129,7 +137,7 @@ async function getForDbName({
user: postgresUsername,
password: postgresPassword,
database: userDbName,
...defaultConnectionOptions
...defaultConnectionOptions,
})
} catch (e) {
logMessage({
Expand All @@ -148,7 +156,9 @@ async function getForDbName({
message: `A database already exists with the name ${dbName}, please enter a name for the database:`,
default: dbName,
validate: (input) => {
return typeof input === "string" && input.length > 0 && input !== dbName
return (
typeof input === "string" && input.length > 0 && input !== dbName
)
},
},
])
Expand All @@ -167,7 +177,7 @@ async function getForDbName({
return {
client,
dbConnectionString,
dbName
dbName,
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/cli/create-medusa-app/src/utils/facts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const facts = [
"The event bus module is responsible for triggering events and relaying them to subscribers.",
"The cache module is responsible for caching data that requires heavy computation.",
"A workflow is a series of steps that are defined once and executed anywhere. Workflows are created under the src/workflows directory.",
"A workflow's steps can be retried or rolled back in case of an error."
"A workflow's steps can be retried or rolled back in case of an error.",
]

export const getFact = () => {
Expand Down
6 changes: 3 additions & 3 deletions packages/cli/create-medusa-app/src/utils/nextjs-utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import inquirer from "inquirer"
import { exec } from "child_process"
import execute from "./execute.js"
import { FactBoxOptions, displayFactBox } from "./facts.js"
import { displayFactBox, FactBoxOptions } from "./facts.js"
import fs from "fs"
import path from "path"
import { customAlphabet } from "nanoid"
Expand Down Expand Up @@ -37,7 +37,7 @@ export async function installNextjsStarter({
abortController,
factBoxOptions,
verbose = false,
processManager
processManager,
}: InstallOptions): Promise<string> {
factBoxOptions.interval = displayFactBox({
...factBoxOptions,
Expand Down Expand Up @@ -72,7 +72,7 @@ export async function installNextjsStarter({
)
const execOptions = {
signal: abortController?.signal,
cwd: nextjsDirectory
cwd: nextjsDirectory,
}
await processManager.runProcess({
process: async () => {
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/create-medusa-app/src/utils/node-version.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export function getNodeVersion(): number {
const [major] = process.versions.node.split('.').map(Number)
const [major] = process.versions.node.split(".").map(Number)

return major
}

export const MIN_SUPPORTED_NODE_VERSION = 20
export const MIN_SUPPORTED_NODE_VERSION = 20
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pg from "pg"

const { Client } = pg

export const DEFAULT_HOST = "localhost"
Expand Down
1 change: 1 addition & 0 deletions packages/cli/medusa-cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
},
"dependencies": {
"@medusajs/utils": "1.11.9",
"@types/express": "^4.17.17",
"chalk": "^4.0.0",
"configstore": "5.0.1",
"dotenv": "^16.4.5",
Expand Down
5 changes: 1 addition & 4 deletions packages/cli/medusa-cli/src/commands/new.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,7 @@ import reporter from "../reporter"
import { getPackageManager, setPackageManager } from "../util/package-manager"
import { PanicId } from "../reporter/panic-handler"
import { clearProject } from "../util/clear-project"
import {
getNodeVersion,
MIN_SUPPORTED_NODE_VERSION,
} from "@medusajs/utils"
import { getNodeVersion, MIN_SUPPORTED_NODE_VERSION } from "@medusajs/utils"

const removeUndefined = (obj) => {
return Object.fromEntries(
Expand Down
22 changes: 11 additions & 11 deletions packages/cli/medusa-dev-cli/src/local-npm-registry/cleanup-tasks.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
const signalExit = require(`signal-exit`);
const signalExit = require(`signal-exit`)

const cleanupTasks = new Set();
const cleanupTasks = new Set()

exports.registerCleanupTask = (taskFn) => {
cleanupTasks.add(taskFn);
cleanupTasks.add(taskFn)
return () => {
const result = taskFn();
cleanupTasks.delete(taskFn);
return result;
};
};
const result = taskFn()
cleanupTasks.delete(taskFn)
return result
}
}

signalExit(() => {
if (cleanupTasks.size) {
console.log(`Process exitted in middle of publishing - cleaning up`);
cleanupTasks.forEach((taskFn) => taskFn());
console.log(`Process exitted in middle of publishing - cleaning up`)
cleanupTasks.forEach((taskFn) => taskFn())
}
});
})
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const getDependantPackages = ({
packagesToPublish.add(packageName)
const dependants = depTree[packageName]
if (dependants) {
dependants.forEach(dependant =>
dependants.forEach((dependant) =>
getDependantPackages({
packageName: dependant,
depTree,
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/medusa-dev-cli/src/utils/promisified-spawn.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const defaultSpawnArgs = {
stdio: `inherit`,
}

exports.setDefaultSpawnStdio = stdio => {
exports.setDefaultSpawnStdio = (stdio) => {
defaultSpawnArgs.stdio = stdio
}

Expand Down
6 changes: 3 additions & 3 deletions packages/cli/medusa-dev-cli/src/utils/version.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
exports.getVersionInfo = () => {
const { version: devCliVersion } = require(`../../package.json`);
return `Medusa Dev CLI version: ${devCliVersion}`;
};
const { version: devCliVersion } = require(`../../package.json`)
return `Medusa Dev CLI version: ${devCliVersion}`
}
30 changes: 23 additions & 7 deletions packages/cli/oas/medusa-oas-cli/src/__tests__/command-oas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,23 @@ import execa from "execa"

/**
* OAS output directory
*
*
* @privateRemarks
* This should be the only directory OAS is loaded from for Medusa V2.
* For now, we only use it if the --v2 flag it passed to the CLI tool.
*/
const oasOutputPath = path.resolve(
__dirname, "..", "..", "..", "..", "..", "..", "www", "utils", "generated", "oas-output"
__dirname,
"..",
"..",
"..",
"..",
"..",
"..",
"www",
"utils",
"generated",
"oas-output"
)
const basePath = path.resolve(__dirname, `../../`)

Expand Down Expand Up @@ -128,7 +138,13 @@ describe("command oas", () => {

beforeAll(async () => {
const outDir = path.resolve(tmpDir, uid())
await runCLI("oas", ["--type", "combined", "--out-dir", outDir, "--local"])
await runCLI("oas", [
"--type",
"combined",
"--out-dir",
outDir,
"--local",
])
const generatedFilePath = path.resolve(outDir, "combined.oas.json")
oas = (await readJson(generatedFilePath)) as OpenAPIObject
})
Expand Down Expand Up @@ -227,7 +243,7 @@ describe("command oas", () => {
outDir,
"--paths",
additionalPath,
"--local"
"--local",
])
const generatedFilePath = path.resolve(outDir, "store.oas.json")
oas = (await readJson(generatedFilePath)) as OpenAPIObject
Expand Down Expand Up @@ -363,7 +379,7 @@ components:
outDir,
"--base",
filePath,
"--local"
"--local",
])
const generatedFilePath = path.resolve(outDir, "store.oas.json")
oas = (await readJson(generatedFilePath)) as OpenAPIObject
Expand Down Expand Up @@ -473,7 +489,7 @@ components:
const routes = Object.keys(oas.paths)
expect(routes.includes("/admin/products")).toBeTruthy()
expect(routes.includes("/store/products")).toBeFalsy()
})
})
})

describe("public OAS with base", () => {
Expand Down Expand Up @@ -579,7 +595,7 @@ components:
])
const generatedFilePath = path.resolve(outDir, "store.oas.json")
oas = (await readJson(generatedFilePath)) as OpenAPIObject
})
})

it("should add new path to existing paths", async () => {
const routes = Object.keys(oas.paths)
Expand Down
50 changes: 39 additions & 11 deletions packages/cli/oas/medusa-oas-cli/src/command-docs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { PreviewDocsOptions, previewDocs } from "@redocly/cli/lib/commands/preview-docs"
import {
previewDocs,
PreviewDocsOptions,
} from "@redocly/cli/lib/commands/preview-docs"
import { commandWrapper } from "@redocly/cli/lib/wrapper"
import { Command, Option, OptionValues } from "commander"
import execa from "execa"
Expand All @@ -12,7 +15,12 @@ import {
} from "./utils/circular-patch-utils"
import { getTmpDirectory, isFile } from "./utils/fs-utils"
import { readJson } from "./utils/json-utils"
import { jsonObjectToYamlString, readYaml, writeYaml, writeYamlFromJson } from "./utils/yaml-utils"
import {
jsonObjectToYamlString,
readYaml,
writeYaml,
writeYamlFromJson,
} from "./utils/yaml-utils"
import yargs from "yargs"

/**
Expand Down Expand Up @@ -64,7 +72,7 @@ export const commandOptions: Option[] = [
new Option(
"--main-file-name <mainFileName>",
"The name of the main YAML file."
).default("openapi.yaml")
).default("openapi.yaml"),
]

export function getCommand(): Command {
Expand Down Expand Up @@ -140,7 +148,10 @@ export async function execute(cliParams: OptionValues): Promise<void> {
if (dryRun) {
console.log(`⚫️ Dry run - no files generated`)
// check out possible changes in redocly config
await execa("git", ["checkout", path.join(basePath, "redocly", "redocly-config.yaml")])
await execa("git", [
"checkout",
path.join(basePath, "redocly", "redocly-config.yaml"),
])
return
}
if (shouldPreview) {
Expand All @@ -150,7 +161,10 @@ export async function execute(cliParams: OptionValues): Promise<void> {
if (shouldSplit) {
await generateReference(srcFileSanitized, outDir)
} else {
await writeYaml(path.join(outDir, finalOASFile), await fs.readFile(srcFileSanitized, "utf8"))
await writeYaml(
path.join(outDir, finalOASFile),
await fs.readFile(srcFileSanitized, "utf8")
)
}
if (shouldBuildHTML) {
const outHTMLFile = path.resolve(outDir, "index.html")
Expand Down Expand Up @@ -236,17 +250,31 @@ const fixCirclularReferences = async (srcFile: string): Promise<void> => {
${hint}
###
`
const redoclyConfigPath = path.join(basePath, "redocly", "redocly-config.yaml")
const originalContent = await readYaml(redoclyConfigPath) as CircularReferenceConfig
const redoclyConfigPath = path.join(
basePath,
"redocly",
"redocly-config.yaml"
)
const originalContent = (await readYaml(
redoclyConfigPath
)) as CircularReferenceConfig
Object.keys(recommendation).forEach((recKey) => {
originalContent.decorators["medusa/circular-patch"].schemas[recKey] = [
...(originalContent.decorators["medusa/circular-patch"].schemas[recKey] || []),
...recommendation[recKey]
...(originalContent.decorators["medusa/circular-patch"].schemas[
recKey
] || []),
...recommendation[recKey],
]
})

await writeYaml(redoclyConfigPath, jsonObjectToYamlString(originalContent))
console.log(`🟡 Added the following unhandled circular references to redocly-config.ts:` + hintMessage)
await writeYaml(
redoclyConfigPath,
jsonObjectToYamlString(originalContent)
)
console.log(
`🟡 Added the following unhandled circular references to redocly-config.ts:` +
hintMessage
)
}
}
console.log(`🟢 All circular references are handled`)
Expand Down
Loading

0 comments on commit 48e0016

Please sign in to comment.