Skip to content
This repository has been archived by the owner on Mar 19, 2024. It is now read-only.

Commit

Permalink
chore: move utils to separate files
Browse files Browse the repository at this point in the history
  • Loading branch information
hanspagel committed Jan 29, 2024
1 parent 22cb2a2 commit 0802b9b
Show file tree
Hide file tree
Showing 8 changed files with 4,419 additions and 4,373 deletions.
8,516 changes: 4,270 additions & 4,246 deletions packages/cli/openapi.json

Large diffs are not rendered by default.

135 changes: 8 additions & 127 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,133 +14,14 @@ import prettyjson from 'prettyjson'
import prompts from 'prompts'
import toml from 'toml-js'
import { version } from '../package.json'
import { getOperationByMethodAndPath } from './utils'

function readFile(file: string) {
try {
return fs.readFileSync(file, 'utf8')
} catch (err) {
console.error(err)
}
}

async function loadOpenApiFile(file: string) {
const validator = new Validator()
const result = await validator.validate(file)

if (result.valid) {
const schema = validator.resolveRefs() as OpenAPI.Document

console.log(
kleur.bold().white('[INFO]'),
kleur.bold().white(schema.info.title),
kleur.grey(`(OpenAPI v${validator.version})`),
)
// Stats
const pathsCount = Object.keys(schema.paths).length

let operationsCount = 0
for (const path in schema.paths) {
for (const method in schema.paths[path]) {
operationsCount++
}
}

console.log(
kleur.bold().white('[INFO]'),
kleur.grey(`${pathsCount} paths, ${operationsCount} operations`),
)

console.log()
} else {
console.warn(
kleur.bold().yellow('[WARN]'),
kleur.yellow('File doesn’t match the OpenAPI specification.'),
)
console.log()
}

return validator
}

function getMethodColor(method: string) {
const colors = {
get: 'green',
post: 'cyan',
put: 'yellow',
delete: 'red',
patch: 'magenta',
}

return colors[method.toLowerCase()] ?? 'grey'
}

function getHtmlDocument(specification: OpenAPI.Document, watch = false) {
return `<!doctype html>
<html>
<head>
<title>API Reference</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1" />
<style>
body {
margin: 0;
}
</style>
${
watch
? `
<script>
const evtSource = new EventSource('__watcher');
evtSource.onmessage = (event) => {
console.log(\`message: \${event.data}\`);
window.location.reload();
};
</script>
`
: ''
}
</head>
<body>
<script
id="api-reference"
type="application/json"
data-proxy-url="https://api.scalar.com/request-proxy">${JSON.stringify(
specification,
)}</script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>`
}

function useGivenFileOrConfiguration(file?: string) {
// If a specific file is given, use it.
if (file) {
return file
}

// Try to load the configuration
try {
const configuration = toml.parse(readFile('scalar.toml'))

if (configuration?.reference?.file) {
return configuration.reference.file
}
} catch {}

console.error(kleur.red('No file provided.'))
console.log()
console.log(
kleur.white(
'Try `scalar init` or add the file as an argument. Read `scalar --help` for more information.',
),
)
console.log()

process.exit(1)
}
import {
getHtmlDocument,
getMethodColor,
getOperationByMethodAndPath,
loadOpenApiFile,
readFile,
useGivenFileOrConfiguration,
} from './utils'

const program = new Command()

Expand Down
44 changes: 44 additions & 0 deletions packages/cli/src/utils/getHtmlDocument.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { OpenAPI } from 'openapi-types'

export function getHtmlDocument(
specification: OpenAPI.Document,
watch = false,
) {
return `<!doctype html>
<html>
<head>
<title>API Reference</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1" />
<style>
body {
margin: 0;
}
</style>
${
watch
? `
<script>
const evtSource = new EventSource('__watcher');
evtSource.onmessage = (event) => {
console.log(\`message: \${event.data}\`);
window.location.reload();
};
</script>
`
: ''
}
</head>
<body>
<script
id="api-reference"
type="application/json"
data-proxy-url="https://api.scalar.com/request-proxy">${JSON.stringify(
specification,
)}</script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>`
}
11 changes: 11 additions & 0 deletions packages/cli/src/utils/getMethodColor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function getMethodColor(method: string) {
const colors = {
get: 'green',
post: 'cyan',
put: 'yellow',
delete: 'red',
patch: 'magenta',
}

return colors[method.toLowerCase()] ?? 'grey'
}
5 changes: 5 additions & 0 deletions packages/cli/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export * from './getHtmlDocument'
export * from './getMethodColor'
export * from './getOperationByMethodAndPath'
export * from './loadOpenApiFile'
export * from './readFile'
export * from './useGivenFileOrConfiguration'
42 changes: 42 additions & 0 deletions packages/cli/src/utils/loadOpenApiFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { Validator } from '@seriousme/openapi-schema-validator'
import kleur from 'kleur'
import type { OpenAPI } from 'openapi-types'

export async function loadOpenApiFile(file: string) {
const validator = new Validator()
const result = await validator.validate(file)

if (result.valid) {
const schema = validator.resolveRefs() as OpenAPI.Document

console.log(
kleur.bold().white('[INFO]'),
kleur.bold().white(schema.info.title),
kleur.grey(`(OpenAPI v${validator.version})`),
)
// Stats
const pathsCount = Object.keys(schema.paths).length

let operationsCount = 0
for (const path in schema.paths) {
for (const method in schema.paths[path]) {
operationsCount++
}
}

console.log(
kleur.bold().white('[INFO]'),
kleur.grey(`${pathsCount} paths, ${operationsCount} operations`),
)

console.log()
} else {
console.warn(
kleur.bold().yellow('[WARN]'),
kleur.yellow('File doesn’t match the OpenAPI specification.'),
)
console.log()
}

return validator
}
9 changes: 9 additions & 0 deletions packages/cli/src/utils/readFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import fs from 'node:fs'

export function readFile(file: string) {
try {
return fs.readFileSync(file, 'utf8')
} catch (err) {
console.error(err)
}
}
30 changes: 30 additions & 0 deletions packages/cli/src/utils/useGivenFileOrConfiguration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import kleur from 'kleur'
import toml from 'toml-js'
import { readFile } from './'

export function useGivenFileOrConfiguration(file?: string) {
// If a specific file is given, use it.
if (file) {
return file
}

// Try to load the configuration
try {
const configuration = toml.parse(readFile('scalar.toml'))

if (configuration?.reference?.file) {
return configuration.reference.file
}
} catch {}

console.error(kleur.red('No file provided.'))
console.log()
console.log(
kleur.white(
'Try `scalar init` or add the file as an argument. Read `scalar --help` for more information.',
),
)
console.log()

process.exit(1)
}

0 comments on commit 0802b9b

Please sign in to comment.