Skip to content

feat: add support for arbitrary metadata #70

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 5 commits into from
Oct 18, 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
29 changes: 26 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ console.log(await store.get('my-key'))

## Store API reference

### `get(key: string, { type: string }): Promise<any>`
### `get(key: string, { type?: string }): Promise<any>`

Retrieves an object with the given key.

Expand All @@ -191,7 +191,30 @@ const entry = await blobs.get('some-key', { type: 'json' })
console.log(entry)
```

### `set(key: string, value: ArrayBuffer | Blob | ReadableStream | string): Promise<void>`
### `getWithMetadata(key: string, { type?: string }): Promise<{ data: any, etag: string, metadata: object }>`

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we reference the Metadata type in the return type?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reckon it's ok in the docs to just say object. It's just Record<string, unknown>

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I don't think there's much value in using the custom type here.


Retrieves an object with the given key, the [ETag value](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag)
for the entry, and any metadata that has been stored with the entry.

Depending on the most convenient format for you to access the value, you may choose to supply a `type` property as a
second parameter, with one of the following values:

- `arrayBuffer`: Returns the entry as an
[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
- `blob`: Returns the entry as a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
- `json`: Parses the entry as JSON and returns the resulting object

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what happens if that parsing fails? do we just bubble up the SyntaxError? would it make sense to include a note about what happens?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the same error that you get when parsing an invalid Response will be thrown. I can add a note to the docs.

- `stream`: Returns the entry as a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)
- `text` (default): Returns the entry as a string of plain text

If an object with the given key is not found, `null` is returned.

```javascript
const blob = await blobs.getWithMetadata('some-key', { type: 'json' })

console.log(blob.data, blob.etag, blob.metadata)
```

### `set(key: string, value: ArrayBuffer | Blob | ReadableStream | string, { metadata?: object }): Promise<void>`

Creates an object with the given key and value.

Expand All @@ -201,7 +224,7 @@ If an entry with the given key already exists, its value is overwritten.
await blobs.set('some-key', 'This is a string value')
```

### `setJSON(key: string, value: any): Promise<void>`
### `setJSON(key: string, value: any, { metadata?: object }): Promise<void>`

Convenience method for creating a JSON-serialized object with the given key.

Expand Down
32 changes: 24 additions & 8 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { EnvironmentContext, getEnvironmentContext, MissingBlobsEnvironmentError } from './environment.ts'
import { encodeMetadata, Metadata, METADATA_HEADER_EXTERNAL, METADATA_HEADER_INTERNAL } from './metadata.ts'
import { fetchAndRetry } from './retry.ts'
import { BlobInput, Fetcher, HTTPMethod } from './types.ts'

interface MakeStoreRequestOptions {
body?: BlobInput | null
headers?: Record<string, string>
key: string
metadata?: Metadata
method: HTTPMethod
storeName: string
}
Expand Down Expand Up @@ -33,38 +35,52 @@ export class Client {
this.token = token
}

private async getFinalRequest(storeName: string, key: string, method: string) {
private async getFinalRequest(storeName: string, key: string, method: string, metadata?: Metadata) {
const encodedKey = encodeURIComponent(key)
const encodedMetadata = encodeMetadata(metadata)

if (this.edgeURL) {
const headers: Record<string, string> = {
authorization: `Bearer ${this.token}`,
}

if (encodedMetadata) {
headers[METADATA_HEADER_EXTERNAL] = encodedMetadata
}

return {
headers: {
authorization: `Bearer ${this.token}`,
},
headers,
url: `${this.edgeURL}/${this.siteID}/${storeName}/${encodedKey}`,
}
}

const apiURL = `${this.apiURL ?? 'https://api.netlify.com'}/api/v1/sites/${
this.siteID
}/blobs/${encodedKey}?context=${storeName}`
const headers = { authorization: `Bearer ${this.token}` }
const apiHeaders: Record<string, string> = { authorization: `Bearer ${this.token}` }

if (encodedMetadata) {
apiHeaders[METADATA_HEADER_EXTERNAL] = encodedMetadata
}

const fetch = this.fetch ?? globalThis.fetch
const res = await fetch(apiURL, { headers, method })
const res = await fetch(apiURL, { headers: apiHeaders, method })

if (res.status !== 200) {
throw new Error(`${method} operation has failed: API returned a ${res.status} response`)
}

const { url } = await res.json()
const userHeaders = encodedMetadata ? { [METADATA_HEADER_INTERNAL]: encodedMetadata } : undefined

return {
headers: userHeaders,
url,
}
}

async makeRequest({ body, headers: extraHeaders, key, method, storeName }: MakeStoreRequestOptions) {
const { headers: baseHeaders = {}, url } = await this.getFinalRequest(storeName, key, method)
async makeRequest({ body, headers: extraHeaders, key, metadata, method, storeName }: MakeStoreRequestOptions) {
const { headers: baseHeaders = {}, url } = await this.getFinalRequest(storeName, key, method, metadata)
const headers: Record<string, string> = {
...baseHeaders,
...extraHeaders,
Expand Down
Loading