Skip to content

Commit

Permalink
feat: sequential async operations with spinner output
Browse files Browse the repository at this point in the history
  • Loading branch information
alvarosabu committed Jan 23, 2025
1 parent 31e2b25 commit 4d8fea1
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 39 deletions.
12 changes: 9 additions & 3 deletions src/commands/components/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { join, parse } from 'node:path'
import { resolvePath, saveToFile } from '../../utils/filesystem'
import type { ReadComponentsOptions, SaveComponentsOptions, SpaceComponent, SpaceComponentGroup, SpaceComponentPreset, SpaceData } from './constants'
import { getStoryblokUrl } from '../../utils/api-routes'
import { customFetch } from '../../utils/fetch'
import { customFetch, delay } from '../../utils/fetch'
import { readdir, readFile } from 'node:fs/promises'

export const fetchComponents = async (space: string, token: string, region: RegionCode): Promise<SpaceComponent[] | undefined> => {
Expand Down Expand Up @@ -78,6 +78,7 @@ export const fetchComponentPresets = async (space: string, token: string, region
export const pushComponent = async (space: string, component: SpaceComponent, token: string, region: RegionCode): Promise<SpaceComponent | undefined> => {
try {
const url = getStoryblokUrl(region)

const response = await customFetch<{
component: SpaceComponent
}>(`${url}/spaces/${space}/components`, {
Expand All @@ -87,13 +88,20 @@ export const pushComponent = async (space: string, component: SpaceComponent, to
},
body: JSON.stringify(component),
})
await delay(2000)
return response.component
}
catch (error) {
await delay(2000)
handleAPIError('push_component', error as Error)
}
}

export const fakePushComponent = async (component: SpaceComponent): Promise<SpaceComponent | undefined> => {
await delay(2000)
return component
}

export const saveComponentsToFiles = async (
space: string,
spaceData: SpaceData,
Expand Down Expand Up @@ -195,8 +203,6 @@ export const readComponentsFiles = async (
// Read from separate files
const files = await readdir(resolvedPath, { recursive: true })

console.log('Files:', files)

// Then process files
for (const file of files) {
if (!file.endsWith('.json')) { continue }

Check failure on line 208 in src/commands/components/actions.ts

View workflow job for this annotation

GitHub Actions / Lint (20)

This line has 2 statements. Maximum allowed is 1
Expand Down
54 changes: 20 additions & 34 deletions src/commands/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { colorPalette, commands } from '../../constants'
import { session } from '../../session'
import { getProgram } from '../../program'
import { CommandError, handleError, konsola } from '../../utils'
import { fetchComponent, fetchComponentGroups, fetchComponentPresets, fetchComponents, pushComponent, readComponentsFiles, saveComponentsToFiles } from './actions'
import { fakePushComponent, fetchComponent, fetchComponentGroups, fetchComponentPresets, fetchComponents, pushComponent, readComponentsFiles, saveComponentsToFiles } from './actions'

Check failure on line 6 in src/commands/components/index.ts

View workflow job for this annotation

GitHub Actions / Lint (20)

'pushComponent' is defined but never used
import type { PullComponentsOptions, PushComponentsOptions } from './constants'

import ora from 'ora'
Expand Down Expand Up @@ -54,7 +54,7 @@ componentsCommand
const presets = await fetchComponentPresets(space, state.password, state.region)
spinner2.succeed()

const spinner3 = ora(`Saving ${chalk.hex(colorPalette.COMPONENTS)('components')}`).start()
const spinner3 = ora(`Fetching ${chalk.hex(colorPalette.COMPONENTS)('components')}`).start()
// Save everything using the new structure
let components
if (componentName) {
Expand Down Expand Up @@ -139,46 +139,32 @@ componentsCommand
failed: [] as Array<{ name: string, error: unknown }>,
}

try {
await pushComponent(space, spaceData.components[0], state.password, state.region)
results.successful.push(spaceData.components[0].name)
}
catch (error) {
results.failed.push({
name: spaceData.components[0].name,
error,
})
}
// Process all components sequentially
/* for (const component of spaceData.components) {
// Process components sequentially to maintain clear output
for (const component of spaceData.components) {
const spinner = ora({
text: `Pushing component: ${chalk.hex(colorPalette.COMPONENTS)(component.name)}`,
stream: process.stdout,
}).start()

try {
await pushComponent(space, component, state.password, state.region)
await fakePushComponent(component)
spinner.succeed(`Pushed component: ${chalk.hex(colorPalette.COMPONENTS)(component.name)}`)
results.successful.push(component.name)
}
catch (error) {
results.failed.push({
name: component.name,
error,
})
spinner.fail(`Failed to push component: ${chalk.hex(colorPalette.COMPONENTS)(component.name)}`)
results.failed.push({ name: component.name, error })
}
} */

console.log(results)

// Display summary
konsola.ok(`Successfully pushed ${results.successful.length} components:`)
if (results.successful.length > 0) {
results.successful.forEach(name => konsola.info(`✓ ${name}`))
}

if (results.failed.length > 0) {
konsola.error('', null, {
header: true,
})
konsola.error(`Failed to push ${results.failed.length} components:`)
results.failed.forEach(({ name, error }) => {
konsola.error(`✗ ${name}`, error)
})
if (!verbose) {
konsola.br()
konsola.info('For more information about the error, run the command with the `--verbose` flag')
}
else {
konsola.error('Failed to push components:', results.failed)
}
}

if (filter) {
Expand Down
5 changes: 3 additions & 2 deletions src/utils/error/api-error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export class APIError extends Error {
code: number
messageStack: string[]
error: FetchError | undefined

response: FetchError['response'] | undefined
constructor(errorId: keyof typeof API_ERRORS, action: keyof typeof API_ACTIONS, error?: FetchError, customMessage?: string) {
super(customMessage || API_ERRORS[errorId])
this.name = 'API Error'
Expand All @@ -56,6 +56,7 @@ export class APIError extends Error {
this.code = error?.response?.status || 0
this.messageStack = [API_ACTIONS[action], customMessage || API_ERRORS[errorId]]
this.error = error
this.response = error?.response
}

getInfo() {
Expand All @@ -66,7 +67,7 @@ export class APIError extends Error {
cause: this.cause,
errorId: this.errorId,
stack: this.stack,
data: this.error?.response?.data,
data: this.response?.data,
}
}
}

0 comments on commit 4d8fea1

Please sign in to comment.