Introduction#

GitHub this project shows basics of developing on AWS using TypeScript

  • Setup AWS SDK with TypeScript
  • Basic concepts: Interface, Deconstruct, Enum
  • Experiment S3Client
  • Experiment PollyClient

Setup Project#

Init a new nodejs project as normal

npm init

Then install the typesript complier tsc for this project only

npm install typescript --save-dev

Double check the tsc version

npx tsc --version

Install ambient Node.js types for typescript

npm install @types/node --save-dev

Create a tsconfig.json file

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es6"],
"allowJs": true,
"outDir": "build",
"rootDir": "src",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"resolveJsonModule": true
}
}

Finally create a simple project structure as the following

|--build
|--index.js
|--src
|--index.ts
|--node_modules
|--tsconfig.json
|--package.json
|--package-lock.json

Please take note the package.json

{
"name": "aws-sdk-typescript-demo",
"version": "1.0.0",
"description": "--- author: haimtran date: 01 JUNE 2023 ---",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/node": "^20.2.5",
"typescript": "^5.1.3"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.344.0"
}
}

S3 Client#

Create a simple S3 Client

const s3Client = new S3Client({
region: "us-east-1",
});
// desconstruct input
const listObject = async ({ bucketName }: { bucketName: string }) => {
try {
const res = await s3Client.send(
new ListObjectsCommand({
Bucket: bucketName,
})
);
console.log(res);
} catch (error) {
console.log(error);
}
};
listObject({ bucketName: "cdk-entest-videos" });

Polly Client#

Import to the Polly Client

import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly";

Create Polly Client

const pollyClient = new PollyClient({
region: "ap-southeast-1",
});

Synthesize speech from text

const synthesizeSpeed = async ({ message }: { message: string }) => {
const response = await pollyClient.send(
new SynthesizeSpeechCommand({
Engine: "standard",
LanguageCode: "en-US",
OutputFormat: "mp3",
Text: message,
VoiceId: "Amy",
})
);
console.log("audio stream ", response.AudioStream);
// save audio stream to mp3 file
const audio = await response.AudioStream?.transformToByteArray();
if (audio?.buffer) {
fs.writeFileSync("hello.mp3", Buffer.from(audio.buffer));
} else {
console.log("error audio buffer");
}
// TODO: write to S3 and get pre-signed url
if (response.AudioStream) {
const blob = new Blob([response.AudioStream as Blob]);
const url = URL.createObjectURL(blob);
console.log(url);
}
};

TODO:

  • Write the Audio Stream to S3
  • Serve the Audio Stream right in the browser

Reference#