From 4a4e851d5004848c6713800b8dab6fd9829d4208 Mon Sep 17 00:00:00 2001 From: yasuaki640 Date: Thu, 11 Jul 2024 17:08:36 +0900 Subject: [PATCH] feat(lambda-edge): add `getConnInfo` helper for Lambda@Edge (#3099) * add conninfo helper for lambda@edge * export getConnInfo --- src/adapter/lambda-edge/conninfo.test.ts | 27 ++++++++++++++++++++++++ src/adapter/lambda-edge/conninfo.ts | 15 +++++++++++++ src/adapter/lambda-edge/index.ts | 1 + 3 files changed, 43 insertions(+) create mode 100644 src/adapter/lambda-edge/conninfo.test.ts create mode 100644 src/adapter/lambda-edge/conninfo.ts diff --git a/src/adapter/lambda-edge/conninfo.test.ts b/src/adapter/lambda-edge/conninfo.test.ts new file mode 100644 index 00000000..693f93bc --- /dev/null +++ b/src/adapter/lambda-edge/conninfo.test.ts @@ -0,0 +1,27 @@ +import { Context } from '../../context' +import type { CloudFrontEdgeEvent } from './handler' +import { getConnInfo } from './conninfo' + +describe('getConnInfo', () => { + it('Should info is valid', () => { + const clientIp = Math.random().toString() + const env = { + event: { + Records: [ + { + cf: { + request: { + clientIp, + }, + }, + }, + ], + } as CloudFrontEdgeEvent, + } + + const c = new Context(new Request('http://localhost/'), { env }) + const info = getConnInfo(c) + + expect(info.remote.address).toBe(clientIp) + }) +}) diff --git a/src/adapter/lambda-edge/conninfo.ts b/src/adapter/lambda-edge/conninfo.ts new file mode 100644 index 00000000..d247a322 --- /dev/null +++ b/src/adapter/lambda-edge/conninfo.ts @@ -0,0 +1,15 @@ +import type { GetConnInfo } from '../../helper/conninfo' +import type { CloudFrontEdgeEvent } from './handler' +import type { Context } from '../../context' + +type Env = { + Bindings: { + event: CloudFrontEdgeEvent + } +} + +export const getConnInfo: GetConnInfo = (c: Context) => ({ + remote: { + address: c.env.event.Records[0].cf.request.clientIp, + }, +}) diff --git a/src/adapter/lambda-edge/index.ts b/src/adapter/lambda-edge/index.ts index c7b74f86..b8b2aada 100644 --- a/src/adapter/lambda-edge/index.ts +++ b/src/adapter/lambda-edge/index.ts @@ -4,6 +4,7 @@ */ export { handle } from './handler' +export { getConnInfo } from './conninfo' export type { Callback, CloudFrontConfig,