Skip to content

feat: load context from global variable #87

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 1 commit into from
Nov 2, 2023
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
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ Rather than explicitly passing the configuration context to the `getStore` metho
environment. This is particularly useful for setups where the configuration data is held by one system and the data
needs to be accessed in another system, with no direct communication between the two.

To do this, the system that holds the configuration data should set an environment variable called
`NETLIFY_BLOBS_CONTEXT` with a Base64-encoded, JSON-stringified representation of an object with the following
properties:
To do this, the system that holds the configuration data should set a global variable called `netlifyBlobsContext` or an
environment variable called `NETLIFY_BLOBS_CONTEXT` with a Base64-encoded, JSON-stringified representation of an object
with the following properties:

- `apiURL` (optional) or `edgeURL`: URL of the Netlify API (for [API access](#api-access)) or the edge endpoint (for
[Edge access](#edge-access))
Expand Down
20 changes: 10 additions & 10 deletions src/environment.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { Buffer } from 'node:buffer'
import { env } from 'node:process'

/**
* The name of the environment variable that holds the context in a Base64,
* JSON-encoded object. If we ever need to change the encoding or the shape
* of this object, we should bump the version and create a new variable, so
* that the client knows how to consume the data and can advise the user to
* update the client if needed.
*/
const NETLIFY_CONTEXT_VARIABLE = 'NETLIFY_BLOBS_CONTEXT'
declare global {
// Using `var` so that the declaration is hoisted in such a way that we can
// reference it before it's initialized.
// eslint-disable-next-line no-var
var netlifyBlobsContext: unknown
}

/**
* The context object that we expect in the environment.
Expand All @@ -22,11 +20,13 @@ export interface EnvironmentContext {
}

export const getEnvironmentContext = (): EnvironmentContext => {
if (!env[NETLIFY_CONTEXT_VARIABLE]) {
const context = globalThis.netlifyBlobsContext || env.NETLIFY_BLOBS_CONTEXT

if (typeof context !== 'string' || !context) {
return {}
}

const data = Buffer.from(env[NETLIFY_CONTEXT_VARIABLE], 'base64').toString()
const data = Buffer.from(context, 'base64').toString()

try {
return JSON.parse(data) as EnvironmentContext
Expand Down
140 changes: 99 additions & 41 deletions src/main.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ beforeAll(async () => {

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

const deployID = '6527dfab35be400008332a1d'
Expand Down Expand Up @@ -239,51 +240,108 @@ describe('get', () => {
expect(mockStore.fulfilled).toBeTruthy()
})

test('Loads credentials from the environment', async () => {
const tokens = ['some-token-1', 'another-token-2']
const mockStore = new MockFetch()
.get({
headers: { authorization: `Bearer ${tokens[0]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[0]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[1]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[1]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})

globalThis.fetch = mockStore.fetch

for (let index = 0; index <= 1; index++) {
const context = {
edgeURL,
siteID,
token: tokens[index],
describe('Loads credentials from the environment', () => {
test('From the `NETLIFY_BLOBS_CONTEXT` environment variable', async () => {
const tokens = ['some-token-1', 'another-token-2']
const mockStore = new MockFetch()
.get({
headers: { authorization: `Bearer ${tokens[0]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[0]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[1]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[1]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})

globalThis.fetch = mockStore.fetch

for (let index = 0; index <= 1; index++) {
const context = {
edgeURL,
siteID,
token: tokens[index],
}

env.NETLIFY_BLOBS_CONTEXT = Buffer.from(JSON.stringify(context)).toString('base64')

const store = getStore('images')

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

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

env.NETLIFY_BLOBS_CONTEXT = Buffer.from(JSON.stringify(context)).toString('base64')

const store = getStore('images')

const string = await store.get(key)
expect(string).toBe(value)
expect(mockStore.fulfilled).toBeTruthy()
})

const stream = await store.get(key, { type: 'stream' })
expect(await streamToString(stream as unknown as NodeJS.ReadableStream)).toBe(value)
}
test('From the `netlifyBlobsContext` global variable', async () => {
const tokens = ['some-token-1', 'another-token-2']
const mockStore = new MockFetch()
.get({
headers: { authorization: `Bearer ${tokens[0]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[0]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[1]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})
.get({
headers: { authorization: `Bearer ${tokens[1]}` },
response: new Response(value),
url: `${edgeURL}/${siteID}/images/${key}`,
})

globalThis.fetch = mockStore.fetch

for (let index = 0; index <= 1; index++) {
const context1 = {
edgeURL,
siteID,
token: 'not-the-right-token',
}

env.NETLIFY_BLOBS_CONTEXT = Buffer.from(JSON.stringify(context1)).toString('base64')

const context2 = {
edgeURL,
siteID,
token: tokens[index],
}

globalThis.netlifyBlobsContext = Buffer.from(JSON.stringify(context2)).toString('base64')

const store = getStore('images')

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

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

expect(mockStore.fulfilled).toBeTruthy()
expect(mockStore.fulfilled).toBeTruthy()
})
})
})
})
Expand Down