Skip to content

feat: add connectLambda method #128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,30 @@ const store = getStore('my-store')
console.log(await store.get('my-key'))
```

#### Lambda compatibility mode

The environment is not configured automatically when running functions in the
[Lambda compatibility mode](https://docs.netlify.com/functions/lambda-compatibility). To use Netlify Blobs, you must
initialize the environment manually by calling the `connectLambda` method with the Lambda event as a parameter.

You should call this method immediately before calling `getStore` or `getDeployStore`.

```ts
import { connectLambda, getStore } from '@netlify/blobs'

export const handler = async (event) => {
connectLambda(event)

const store = getStore('my-store')
const value = await store.get('my-key')

return {
statusCode: 200,
body: value,
}
}
```

### API access

You can interact with the blob store through the [Netlify API](https://docs.netlify.com/api/get-started). This is the
Expand Down
6 changes: 6 additions & 0 deletions src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ export const getEnvironmentContext = (): EnvironmentContext => {
return {}
}

export const setEnvironmentContext = (context: EnvironmentContext) => {
const encodedContext = Buffer.from(JSON.stringify(context)).toString('base64')

env.NETLIFY_BLOBS_CONTEXT = encodedContext
}

export class MissingBlobsEnvironmentError extends Error {
constructor(requiredProperties: string[]) {
super(
Expand Down
78 changes: 78 additions & 0 deletions src/lambda_compat.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { env, version as nodeVersion } from 'node:process'

import semver from 'semver'
import { describe, test, expect, beforeAll, afterEach } from 'vitest'

import { MockFetch } from '../test/mock_fetch.js'
import { base64Encode, streamToString } from '../test/util.js'

import { connectLambda } from './lambda_compat.js'
import { getStore } from './main.js'

beforeAll(async () => {
if (semver.lt(nodeVersion, '18.0.0')) {
const nodeFetch = await import('node-fetch')

// @ts-expect-error Expected type mismatch between native implementation and node-fetch
globalThis.fetch = nodeFetch.default
// @ts-expect-error Expected type mismatch between native implementation and node-fetch
globalThis.Request = nodeFetch.Request
// @ts-expect-error Expected type mismatch between native implementation and node-fetch
globalThis.Response = nodeFetch.Response
// @ts-expect-error Expected type mismatch between native implementation and node-fetch
globalThis.Headers = nodeFetch.Headers
}
})

afterEach(() => {
delete env.NETLIFY_BLOBS_CONTEXT
})

const deployID = '6527dfab35be400008332a1d'
const siteID = '9a003659-aaaa-0000-aaaa-63d3720d8621'
const key = '54321'
const value = 'some value'
const edgeToken = 'some other token'
const edgeURL = 'https://edge.netlify'

describe('With edge credentials', () => {
test('Loads the credentials set via the `connectLambda` method', async () => {
const mockLambdaEvent = {
blobs: base64Encode({ token: edgeToken, url: edgeURL }),
headers: {
'x-nf-deploy-id': deployID,
'x-nf-site-id': siteID,
},
}
const mockStore = new MockFetch()
.get({
headers: { authorization: `Bearer ${edgeToken}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/production/${key}`,
})
.get({
headers: { authorization: `Bearer ${edgeToken}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/production/${key}`,
})

globalThis.fetch = mockStore.fetch

connectLambda(mockLambdaEvent)

const blobs = getStore({
edgeURL,
name: 'production',
token: edgeToken,
siteID,
})

const string = await blobs.get(key)
expect(string).toBe(value)

const stream = await blobs.get(key, { type: 'stream' })
expect(await streamToString(stream as unknown as NodeJS.ReadableStream)).toBe(value)

expect(mockStore.fulfilled).toBeTruthy()
})
})
22 changes: 22 additions & 0 deletions src/lambda_compat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { Buffer } from 'node:buffer'

import { EnvironmentContext, setEnvironmentContext } from './environment.ts'
import type { LambdaEvent } from './types.ts'

interface BlobsEventData {
token: string
url: string
}

export const connectLambda = (event: LambdaEvent) => {
const rawData = Buffer.from(event.blobs, 'base64')
const data = JSON.parse(rawData.toString('ascii')) as BlobsEventData
const environmentContext: EnvironmentContext = {
deployID: event.headers['x-nf-deploy-id'],
edgeURL: data.url,
siteID: event.headers['x-nf-site-id'],
token: data.token,
}

setEnvironmentContext(environmentContext)
}
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,9 @@ export enum HTTPMethod {
HEAD = 'head',
PUT = 'put',
}

// TODO: Import the full type from `@netlify/functions`.
export interface LambdaEvent {
blobs: string
headers: Record<string, string>
}