📄 Push API Spec to SwaggerHub #6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Push API Spec to SwaggerHub | |
on: | |
workflow_dispatch: | |
inputs: | |
api-name: | |
type: choice | |
description: API Name | |
options: | |
- products-api | |
- users-api | |
required: true | |
api-version: | |
description: API Version | |
required: true | |
default: 1.0.0 | |
env: | |
SWAGGERHUB_API_KEY: ${{ secrets.SWAGGERHUB_API_KEY }} | |
USERNAME: ${{ secrets.SWAGGERHUB_USERNAME }} | |
jobs: | |
push-spec: | |
runs-on: ubuntu-latest | |
steps: | |
- uses: actions/checkout@v4 | |
- uses: actions/setup-node@v4 | |
with: | |
node-version: '20' | |
- name: Install Dependencies | |
run: | | |
cd apps/${{ github.event.inputs.api-name }} | |
npm install | |
- name: Generate Spec | |
run: | | |
cd apps/${{ github.event.inputs.api-name }} | |
# Create spec generator | |
cat > generate-spec.ts << 'EOL' | |
import { NestFactory } from '@nestjs/core'; | |
import { SwaggerModule } from '@nestjs/swagger'; | |
import { writeFileSync } from 'fs'; | |
import { AppModule } from './src/app.module'; | |
import { swaggerConfig } from './src/config/swagger.config'; | |
async function generateSpec() { | |
let app; | |
try { | |
app = await NestFactory.create(AppModule); | |
const document = SwaggerModule.createDocument(app, swaggerConfig); | |
writeFileSync('openapi-spec.json', JSON.stringify(document, null, 2)); | |
console.log('✨ OpenAPI spec generated successfully'); | |
} catch (error) { | |
console.error('Failed to generate OpenAPI spec:', | |
error instanceof Error ? error.message : error); | |
process.exit(1); | |
} finally { | |
if (app) await app.close(); | |
} | |
} | |
generateSpec(); | |
EOL | |
npx ts-node generate-spec.ts | |
- name: Push to SwaggerHub | |
run: | | |
cd apps/${{ github.event.inputs.api-name }} | |
API_NAME_WITH_PREFIX="sample-${{ github.event.inputs.api-name }}" | |
API_NAME_AND_VERSION="${{ github.event.inputs.api-name }} v${{ github.event.inputs.api-version }}" | |
if swaggerhub api:update ${USERNAME}/${API_NAME_WITH_PREFIX}/${{ github.event.inputs.api-version }} --file openapi-spec.json; then | |
echo "✨ Successfully updated $API_NAME_AND_VERSION on SwaggerHub" | |
else | |
echo "Update $API_NAME_AND_VERSION failed, trying to create..." | |
# If update fails, try to create | |
if swaggerhub api:create ${USERNAME}/${API_NAME_WITH_PREFIX}/${{ github.event.inputs.api-version }} --file openapi-spec.json; then | |
echo "✨ Successfully created $API_NAME_AND_VERSION on SwaggerHub" | |
else | |
echo "Failed to push $API_NAME_AND_VERSION to SwaggerHub" | |
exit 1 | |
fi | |
fi |