AWS SDK 설치
npm install aws-sdk
Controller 생성
import { Controller, Post, Body } from '@nestjs/common';
import { AwsService } from './aws.service';
@Controller('subdomain')
export class SubdomainController {
constructor(private readonly awsService: AwsService) {}
@Post()
async createSubdomain(@Body() body: { subdomain: string }): Promise<{ subdomain: string }> {
const subdomainName = body.subdomain;
const createdSubdomain = await this.awsService.createSubdomain(subdomainName);
return { subdomain: createdSubdomain };
}
}
Service 생성
import { Injectable } from '@nestjs/common';
import * as AWS from 'aws-sdk';
@Injectable()
export class AwsService {
private readonly route53: AWS.Route53;
constructor() {
AWS.config.update({ region: 'YOUR_AWS_REGION' });
this.route53 = new AWS.Route53();
}
async createSubdomain(subdomainName: string): Promise<string> {
const hostedZoneId = 'YOUR_HOSTED_ZONE_ID';
const domainName = 'formflet.io';
const changeBatch = {
Changes: [
{
Action: 'UPSERT',
ResourceRecordSet: {
Name: `${subdomainName}.${domainName}`,
Type: 'CNAME',
TTL: 300,
ResourceRecords: [
{
Value: 'YOUR_TARGET_VALUE',
},
],
},
},
],
};
const params = {
ChangeBatch: changeBatch,
HostedZoneId: hostedZoneId,
};
try {
await this.route53.changeResourceRecordSets(params).promise();
return `${subdomainName}.${domainName}`;
} catch (error) {
console.error(error);
throw new Error('Error creating subdomain');
}
}
}
- 'YOUR_AWS_REGION', 'YOUR_HOSTED_ZONE_ID', 'YOUR_TARGET_VALUE'는 실제 값으로 설정.
module 수정
import { Module } from '@nestjs/common';
import { SubdomainController } from './subdomain.controller';
import { AwsService } from './aws.service';
@Module({
controllers: [SubdomainController],
providers: [AwsService],
})
export class SubdomainModule {}
- app.module.ts 에서 SubdomainModule import.
Copy code
import { Module } from '@nestjs/common';
import { SubdomainModule } from './subdomain/subdomain.module';
@Module({
imports: [SubdomainModule],
})
export class AppModule {}