Skip to content

Commit

Permalink
feat: generate badges in multiple styles
Browse files Browse the repository at this point in the history
  • Loading branch information
NimmLor committed Apr 2, 2023
1 parent cf87101 commit 154f8b8
Show file tree
Hide file tree
Showing 10 changed files with 80 additions and 47 deletions.
2 changes: 1 addition & 1 deletion .projenrc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const project = new awscdk.AwsCdkConstructLibrary({
project.setScript('cdk', 'cdk')
project.setScript(
'e2e',
'yarn build && yarn cdk deploy --app "./lib/integ.default.js" --profile sandbox-h --require-approval never'
'yarn build && yarn cdk deploy --app "./lib/integ.default.js" --require-approval never'
)

const buildLambdaTask = project.preCompileTask
Expand Down
9 changes: 5 additions & 4 deletions API.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Generate Badges for your cloudformation stacks.
```ts
new CdkBadges(stack, 'Badges', {
additionalCfnStacks: [],
badgeStyle: 'flat-square',
badgeStyles: ['flat-square'],
cacheControl: 'max-age=300',
localization: {
hour12: false,
Expand Down
54 changes: 28 additions & 26 deletions lambda/src/events-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { getCfStatusBadge } from './cf-badges'
import { getCfBadgeKeys } from './filenames'
import { updateStackResourceCountBadge } from './trigger-handler'
import { writeBadgeToS3 } from './utils'
import { LambdaEnvironment, writeBadgeToS3 } from './utils'
import type { StackStatus } from '@aws-sdk/client-cloudformation'
import type { EventBridgeEvent, EventBridgeHandler } from 'aws-lambda'

Expand Down Expand Up @@ -39,31 +39,33 @@ export const eventsHandler: EventBridgeHandler<string, unknown, void> = async (
const stackName =
event.detail['stack-id'].split(':stack/')[1].split('/')[0] ?? 'default'

badges.push(
{
filekey: getCfBadgeKeys(stackName).status,
svg: getCfStatusBadge({ status, updatedAt }),
},
{
filekey: getCfBadgeKeys(stackName).namedStatus,
svg: getCfStatusBadge(
{ status, updatedAt },
{ label: `${stackName} Stack` }
),
},
{
filekey: getCfBadgeKeys(stackName).statusDetailed,
svg: getCfStatusBadge({ status, updatedAt }, {}, true),
},
{
filekey: getCfBadgeKeys(stackName).namedStatusDetailed,
svg: getCfStatusBadge(
{ status, updatedAt },
{ label: `${stackName} Stack` },
true
),
}
)
for (const style of LambdaEnvironment.BADGE_STYLES) {
badges.push(
{
filekey: getCfBadgeKeys(stackName, style).status,
svg: getCfStatusBadge({ status, updatedAt }, { style }),
},
{
filekey: getCfBadgeKeys(stackName, style).namedStatus,
svg: getCfStatusBadge(
{ status, updatedAt },
{ label: `${stackName} Stack`, style }
),
},
{
filekey: getCfBadgeKeys(stackName, style).statusDetailed,
svg: getCfStatusBadge({ status, updatedAt }, { style }, true),
},
{
filekey: getCfBadgeKeys(stackName, style).namedStatusDetailed,
svg: getCfStatusBadge(
{ status, updatedAt },
{ label: `${stackName} Stack`, style },
true
),
}
)
}
}

promises.push(
Expand Down
14 changes: 7 additions & 7 deletions lambda/src/filenames.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
export const getCfBadgeKeys = (stackName = 'default') => ({
namedResourceCount: `cf/${stackName}/named-resource-count.svg`,
namedStatus: `cf/${stackName}/named-status-named.svg`,
namedStatusDetailed: `cf/${stackName}/named-status-detailed.svg`,
resourceCount: `cf/${stackName}/resource-count.svg`,
status: `cf/${stackName}/status.svg`,
statusDetailed: `cf/${stackName}/status-detailed.svg`,
export const getCfBadgeKeys = (stackName: string, style: string) => ({
namedResourceCount: `cf/${stackName}/named-resource-count/${style}.svg`,
namedStatus: `cf/${stackName}/named-status-named/${style}.svg`,
namedStatusDetailed: `cf/${stackName}/named-status-detailed/${style}.svg`,
resourceCount: `cf/${stackName}/resource-count/${style}.svg`,
status: `cf/${stackName}/status/${style}.svg`,
statusDetailed: `cf/${stackName}/status-detailed/${style}.svg`,
})
8 changes: 7 additions & 1 deletion lambda/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3'
import type { Format } from 'badge-maker'

export type StackInfo = Partial<{
createdAt: Stack['CreationTime']
Expand All @@ -34,6 +35,7 @@ const {
STACK_NAME,
BUCKET_NAME,
SHOW_SECONDS,
BADGE_STYLES,
} = process.env

if (
Expand All @@ -44,12 +46,16 @@ if (
BASE_URL === undefined ||
STACK_NAME === undefined ||
BUCKET_NAME === undefined ||
SHOW_SECONDS === undefined
SHOW_SECONDS === undefined ||
BADGE_STYLES === undefined
) {
throw new Error('Missing required environment variables')
}

export const LambdaEnvironment = {
BADGE_STYLES: BADGE_STYLES.split(';').filter(Boolean) as Array<
Format['style'] & string
>,
BASE_URL,
BUCKET_NAME,
CACHE_CONTROL,
Expand Down
18 changes: 16 additions & 2 deletions lambda/src/webapp-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,23 @@
import { LambdaEnvironment, listS3Badges } from './utils'
import { render } from './webapp/entry'
import type { APIGatewayProxyHandlerV2 } from 'aws-lambda'
import type { Request, Response } from 'lambda-api'
import createApi from 'lambda-api'

const { STACK_NAME } = LambdaEnvironment
const { STACK_NAME, BASE_URL } = LambdaEnvironment

export const functionUrlHandler: APIGatewayProxyHandlerV2<unknown> = async (
event,
context
) => {
const api = createApi()

api.get('*', async (_request, response) => {
api.use((_request: Request, response: Response, next) => {
response.cors({ headers: '*', methods: 'GET' })
next()
})

api.get('/', async (_request, response) => {
const [s3Badges] = await Promise.all([listS3Badges()])

const html = render(`
Expand Down Expand Up @@ -42,5 +48,13 @@ ${s3Badges
response.status(200).html(html)
})

api.get('/badges', async (_request, response) => {
const [s3Badges] = await Promise.all([listS3Badges()])

response
.status(200)
.json({ badges: s3Badges, baseUrl: BASE_URL, stackName: STACK_NAME })
})

return await api.run(event, context)
}
2 changes: 1 addition & 1 deletion package.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 13 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,10 @@ export interface CdkBadgesProps {

/**
* The style of the badge to generate.
*
* @default ['flat-square', 'flat', 'for-the-badge', 'plastic']
*/
readonly badgeStyle?: BadgeStyle
readonly badgeStyles?: BadgeStyle[]

/**
* The cache control header to use when writing badges to S3.
Expand All @@ -97,19 +99,27 @@ export class CdkBadges extends Construct {
additionalCfnStacks,
cacheControl,
localization,
badgeStyle,
badgeStyles,
addPreviewWebapp,
} = props

this.hostingBucket = new aws_s3.Bucket(this, 'hostingBucket', {
publicReadAccess: true,
})

const badgeStylesString = badgeStyles?.join(';')
const defaultStyles = [
'flat-square',
'flat',
'for-the-badge',
'plastic',
].join(';')

this.lambdaHandler = new aws_lambda.Function(this, 'Handler', {
code: aws_lambda.Code.fromAsset(path.join(__dirname, '../lib/lambda')),
description: 'Generate status badges for cdk resources.',
environment: {
BADGE_STYLE: badgeStyle ?? 'flat-square',
BADGE_STYLES: badgeStylesString ?? defaultStyles,
BASE_URL: `https://${this.hostingBucket.bucketName}.s3.${
Stack.of(this).region
}.amazonaws.com`,
Expand Down
2 changes: 1 addition & 1 deletion src/integ.default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ new CdkBadges(stack, 'Badges', {
'arn:aws:cloudformation:eu-central-1:123456789012:stack/MyStack/12345678-1234-1234-1234-123456789012',
],
addPreviewWebapp: true,
badgeStyle: 'flat-square',
badgeStyles: ['flat-square'],
cacheControl: 'max-age=300',
localization: {
hour12: false,
Expand Down

0 comments on commit 154f8b8

Please sign in to comment.