Skip to content

Commit 413d68c

Browse files
authored
Merge pull request #6 from fourTheorem/cleanse-typescript
style: update tsconfig and Middy type usage
2 parents 483d868 + 3a099c5 commit 413d68c

31 files changed

Lines changed: 3004 additions & 4486 deletions

.eslintrc.js

Lines changed: 0 additions & 15 deletions
This file was deleted.

.gitignore

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,4 +204,7 @@ $RECYCLE.BIN/
204204
*.js
205205
!.eslintrc.js
206206
*.js.map
207-
samconfig.toml
207+
samconfig.toml
208+
*.d.ts
209+
.vscode/
210+

bin/summarise.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
#!/usr/bin/env ./node_modules/.bin/ts-node
22

3-
import { readFileSync } from 'fs'
3+
import { readFileSync } from 'node:fs'
44
import { createSummary } from '../lib/summarisation'
55

66
import yargs from 'yargs'
7-
import { Transcript } from '../lib/types'
7+
import type { Transcript } from '../lib/types'
88

99
interface Argv {
1010
transcriptFilePath: string
@@ -15,20 +15,19 @@ const argv: Argv = yargs
1515
.usage('Usage: $0 <transcriptFilePath>')
1616
.command('$0 <transcriptFilePath>', 'path to the transcript JSON file')
1717
.options('bedrock-region', {
18-
default: 'us-east-1'
18+
default: 'us-east-1',
1919
})
2020
.alias('h', 'help')
2121
.help('help')
22-
.demandCommand(1, 'You need to provide a filename argument.')
23-
.argv as unknown as Argv
22+
.demandCommand(1, 'You need to provide a filename argument.').argv as unknown as Argv
2423

2524
const filename: string = argv.transcriptFilePath
2625
const transcriptContents = readFileSync(filename, 'utf8')
2726
const transcript = JSON.parse(transcriptContents)
2827

2928
summarise(transcript)
3029

31-
async function summarise (transcript: Transcript): Promise<void> {
30+
async function summarise(transcript: Transcript): Promise<void> {
3231
const summary = await createSummary(transcript, { bedrockRegion: argv.bedrockRegion })
3332
console.log(JSON.stringify(summary, null, 4))
3433
}

biome.json

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
3+
"vcs": {
4+
"enabled": true,
5+
"clientKind": "git",
6+
"useIgnoreFile": true
7+
},
8+
"files": {
9+
"ignoreUnknown": false,
10+
"ignore": []
11+
},
12+
"formatter": {
13+
"enabled": true,
14+
"indentStyle": "space",
15+
"indentWidth": 2,
16+
"lineWidth": 120
17+
},
18+
"organizeImports": {
19+
"enabled": true
20+
},
21+
"linter": {
22+
"enabled": true,
23+
"rules": {
24+
"recommended": true
25+
}
26+
},
27+
"javascript": {
28+
"formatter": {
29+
"quoteStyle": "single",
30+
"semicolons": "asNeeded"
31+
}
32+
}
33+
}

events/sample-pr-event.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,4 @@
3535
]
3636
},
3737
"transcriptKey": "processed-transcripts/998.json"
38-
}
38+
}

functions/pull-request/app.ts

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import path from 'node:path'
2-
import { tmpdir } from 'node:os'
31
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
4-
import { simpleGit } from 'simple-git'
5-
import { SSMClient, GetParameterCommand } from '@aws-sdk/client-ssm'
2+
import { tmpdir } from 'node:os'
3+
import path from 'node:path'
64
import { S3Client } from '@aws-sdk/client-s3'
5+
import { GetParameterCommand, SSMClient } from '@aws-sdk/client-ssm'
76
import { Octokit } from 'octokit'
7+
import { simpleGit } from 'simple-git'
88

99
import envs from '../../lib/envs'
10-
import type { Summary } from '../../lib/types'
1110
import { logger, middify } from '../../lib/lambda-common'
11+
import type { Summary } from '../../lib/types'
1212
import { getS3JSON } from '../../lib/utils'
1313
import { createPullRequestDescription } from './pr-description'
1414

@@ -21,10 +21,12 @@ const ssmClient = new SSMClient({})
2121
const s3Client = new S3Client({})
2222

2323
// A personal access token is used to clone and push from/to GitHub
24-
const gitHubUserCredentialsPromise = ssmClient.send(new GetParameterCommand({
25-
Name: GIT_HUB_CREDENTIALS_SSM_PARAMETER,
26-
WithDecryption: true
27-
}))
24+
const gitHubUserCredentialsPromise = ssmClient.send(
25+
new GetParameterCommand({
26+
Name: GIT_HUB_CREDENTIALS_SSM_PARAMETER,
27+
WithDecryption: true,
28+
}),
29+
)
2830

2931
interface PullRequestEvent {
3032
transcriptKey: string
@@ -59,7 +61,9 @@ export const handleEvent = middify(async (event: PullRequestEvent) => {
5961
}
6062
const [username, password] = gitHubUserCredentials.split(':')
6163
if (username === undefined || password === undefined || username === '' || password === '') {
62-
throw new Error(`${GIT_HUB_CREDENTIALS_SSM_PARAMETER} SSM Parameter should be in the format <Username>:<GitHubPersonalAccessToken>`)
64+
throw new Error(
65+
`${GIT_HUB_CREDENTIALS_SSM_PARAMETER} SSM Parameter should be in the format <Username>:<GitHubPersonalAccessToken>`,
66+
)
6367
}
6468

6569
const gitUrl = new URL(GIT_REPO_URL)
@@ -97,9 +101,14 @@ export const handleEvent = middify(async (event: PullRequestEvent) => {
97101
const base = TARGET_BRANCH === undefined ? 'main' : TARGET_BRANCH
98102
const repoPath = gitUrl.pathname
99103
const [, owner] = repoPath.split('/')
100-
const response = await octokit.request(
101-
`POST /repos/${owner}/${repoName}/pulls`, { owner, title, body, head, base, repo: repoName }
102-
)
104+
const response = await octokit.request(`POST /repos/${owner}/${repoName}/pulls`, {
105+
owner,
106+
title,
107+
body,
108+
head,
109+
base,
110+
repo: repoName,
111+
})
103112
const prUrl = response.data.html_url
104113
console.log('Created PR', { prUrl })
105114
return { prUrl }

functions/pull-request/pr-description.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
import { Summary } from '../../lib/types'
1+
import type { Summary } from '../../lib/types'
22

33
/**
44
* Convert decimal seconds to mm:ss format
55
*
66
* @param seconds seconds
77
* @returns a string like '00:00' or '123:59'
88
*/
9-
export function secondsToYtTime (seconds: number): string {
9+
export function secondsToYtTime(seconds: number): string {
1010
const hours = String(Math.floor(seconds / 3600))
11-
const minutes = String(Math.floor(seconds % 3600 / 60))
11+
const minutes = String(Math.floor((seconds % 3600) / 60))
1212
const roundedSeconds = String(Math.floor(seconds % 60))
1313
let res = ''
1414
if (hours !== '0') {
@@ -21,8 +21,8 @@ export function secondsToYtTime (seconds: number): string {
2121
/**
2222
* Create a PR markdown description from the generated summary of the episode and chapters
2323
*/
24-
export function createPullRequestDescription (summary: Summary): string {
25-
const ytChapters = summary.chapters.map(c => `${secondsToYtTime(c.startTimestamp)} ${c.summary}`).join('\n')
24+
export function createPullRequestDescription(summary: Summary): string {
25+
const ytChapters = summary.chapters.map((c) => `${secondsToYtTime(c.startTimestamp)} ${c.summary}`).join('\n')
2626
return `
2727
# Transcript
2828

functions/summary/app.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import path from 'node:path'
2-
import { S3Client } from '@aws-sdk/client-s3'
32
import { MetricUnits } from '@aws-lambda-powertools/metrics'
3+
import { S3Client } from '@aws-sdk/client-s3'
44

55
import envs from '../../lib/envs'
66
import { logger, metrics, middify, tracer } from '../../lib/lambda-common'
7-
import { getS3JSON } from '../../lib/utils'
87
import { createSummary } from '../../lib/summarisation'
9-
import { Summary, Transcript } from '../../lib/types'
8+
import type { Summary, Transcript } from '../../lib/types'
9+
import { getS3JSON } from '../../lib/utils'
1010

1111
const { BUCKET_NAME } = envs
1212

@@ -36,6 +36,6 @@ export const handleEvent = middify(async (event: SummarisationEvent): Promise<Su
3636
metrics.addMetric('ChapterCount', MetricUnits.Count, summary.chapters.length)
3737

3838
return {
39-
summary
39+
summary,
4040
}
4141
})

lib/envs.ts

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,17 @@ type Environment = Record<string, string>
55
* `env.BUCKET_NAME` will throw an Error if BUCKET_NAME is not defined in the environment.
66
* This eliminates the need to check the existence of each environment variable where it is used.
77
*/
8-
const envProxy: Environment = new Proxy({}, {
9-
get (_target: Record<string, string>, name: string): string {
10-
const value = process.env[name]
11-
if (value === undefined) {
12-
throw new Error(`Environment variable ${name} is not set`)
13-
}
14-
return value
15-
}
16-
})
8+
const envProxy: Environment = new Proxy(
9+
{},
10+
{
11+
get(_target: Record<string, string>, name: string): string {
12+
const value = process.env[name]
13+
if (value === undefined) {
14+
throw new Error(`Environment variable ${name} is not set`)
15+
}
16+
return value
17+
},
18+
},
19+
)
1720

1821
export default envProxy

lib/lambda-common.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,28 @@ import { Logger, injectLambdaContext } from '@aws-lambda-powertools/logger'
22
import { Metrics, logMetrics } from '@aws-lambda-powertools/metrics'
33
import { Tracer, captureLambdaHandler } from '@aws-lambda-powertools/tracer'
44
import middy from '@middy/core'
5-
import { Handler } from 'aws-lambda'
5+
import type { Context } from 'aws-lambda'
66

77
// Exported powertools instances for use anywhere within a Lambda function implementation
88
export const logger = new Logger()
99
export const tracer = new Tracer()
1010
export const metrics = new Metrics()
1111

12+
export type LambdaPromiseHandler<TEvent, TResult> = (event: TEvent, context: Context) => Promise<TResult>
13+
1214
/**
1315
* Create a wrapped Lambda Function handler with injected powertools logger, tracer and metrics
1416
*
1517
* @param handler The undecorated Lambda Function handler
1618
* @returns A 'middified' handler
1719
*/
18-
export const middify = (handler: Handler): Handler => {
19-
return middy(handler)
20+
21+
export const middify = <TEvent, TResult>(
22+
handler: LambdaPromiseHandler<TEvent, TResult>,
23+
): LambdaPromiseHandler<TEvent, TResult> => {
24+
return middy<TEvent, TResult>()
2025
.use(injectLambdaContext(logger, { logEvent: true }))
2126
.use(logMetrics(metrics))
2227
.use(captureLambdaHandler(tracer))
28+
.handler(handler)
2329
}

0 commit comments

Comments
 (0)