Hono on Cloudflare with SST
SST를 사용하여 Cloudflare에서 Hono API를 생성하고 배포합니다.
SST와 함께 Cloudflare에서 Hono 사용하기
Hono로 API를 구축하고, 파일 업로드를 위한 R2 버킷을 추가한 다음, SST를 사용해 Cloudflare에 배포해 보겠습니다.
시작하기 전에 Cloudflare API 토큰 생성을 완료하세요.
1. 프로젝트 생성
우리 앱을 만들어 보겠습니다.
mkdir my-hono-api && cd my-hono-apinpm init -ySST 초기화
이제 앱에서 SST를 초기화해 보겠습니다.
npx sst@latest initnpm install기본값을 선택하고 Cloudflare를 선택합니다. 이렇게 하면 프로젝트 루트에 sst.config.ts 파일이 생성됩니다.
Cloudflare API 토큰 설정
Cloudflare API 토큰은 .env 파일에 저장하거나 직접 설정할 수 있습니다.
export CLOUDFLARE_API_TOKEN=aaaaaaaa_aaaaaaaaaaaa_aaaaaaaaexport CLOUDFLARE_DEFAULT_ACCOUNT_ID=aaaaaaaa_aaaaaaaaaaaa_aaaaaaaa2. Worker 추가하기
Worker를 추가해 보겠습니다. sst.config.ts 파일을 업데이트하세요.
async run() { const hono = new sst.cloudflare.Worker("Hono", { url: true, handler: "index.ts", });
return { api: hono.url, };}Worker URL을 활성화하여 API로 사용할 수 있도록 설정했습니다.
3. R2 버킷 추가하기
파일 업로드를 위해 R2 버킷을 추가해 보겠습니다. sst.config.ts 파일을 업데이트하세요.
const bucket = new sst.cloudflare.Bucket("MyBucket");이 코드를 Worker 컴포넌트 위에 추가하세요.
버킷 연결하기
이제 버킷을 Worker에 연결합니다.
const hono = new sst.cloudflare.Worker("Hono", { url: true, link: [bucket], handler: "index.ts",});4. 파일 업로드
API의 / 라우트에서 R2 버킷에 파일을 업로드하려고 합니다. index.ts 파일을 생성하고 다음 코드를 추가하세요.
const app = new Hono() .put("/*", async (c) => { const key = crypto.randomUUID(); await Resource.MyBucket.put(key, c.req.raw.body, { httpMetadata: { contentType: c.req.header("content-type"), }, }); return c.text(`Object created with key: ${key}`); });
export default app;필요한 모듈을 임포트하세요.
import { Hono } from "hono";import { Resource } from "sst";그리고 npm 패키지를 설치하세요.
npm install hono5. 파일 다운로드
API에 GET 요청을 보내면 마지막으로 업로드된 파일을 다운로드할 수 있습니다. 이를 index.ts의 라우트에 추가하세요.
const app = new Hono() // ... .get("/", async (c) => { const first = await Resource.MyBucket.list().then( (res) => res.objects.sort( (a, b) => a.uploaded.getTime() - b.uploaded.getTime(), )[0], ); const result = await Resource.MyBucket.get(first.key); c.header("content-type", result.httpMetadata.contentType); return c.body(result.body); });Resource.MyBucket.list()를 사용해 버킷에 있는 파일 목록을 가져오고, Resource.MyBucket.get()을 사용해 주어진 키에 해당하는 파일을 가져옵니다.
개발 모드 시작
앱을 개발 모드로 실행합니다.
npx sst dev이 명령어를 실행하면 API의 URL을 확인할 수 있습니다.
✓ 완료 Hono: https://my-hono-api-jayair-honoscript.sst-15d.workers.dev앱 테스트하기
프로젝트 루트에서 파일을 업로드해 보겠습니다. 여러분의 API URL을 사용해야 합니다.
curl -H --upload-file package.json https://my-hono-api-jayair-honoscript.sst-15d.workers.dev이제 브라우저에서 https://my-hono-api-jayair-honoscript.sst-15d.workers.dev로 이동하면 방금 업로드한 파일이 로드됩니다.
6. 앱 배포하기
마지막으로 앱을 배포해 보겠습니다!
npx sst deploy --stage production여기서는 어떤 스테이지 이름을 사용해도 되지만, 프로덕션을 위해 새로운 스테이지를 만드는 것이 좋습니다.