@vercel/blob
Advanced tools
Comparing version 0.6.3 to 0.7.0
@@ -25,2 +25,12 @@ import { Readable } from 'node:stream'; | ||
} | ||
interface ListBlobResult { | ||
blobs: HeadBlobResult[]; | ||
cursor?: string; | ||
hasMore: boolean; | ||
} | ||
interface ListCommandOptions extends BlobCommandOptions { | ||
limit?: number; | ||
prefix?: string; | ||
cursor?: string; | ||
} | ||
interface BlobCommandOptions { | ||
@@ -37,3 +47,4 @@ token?: string; | ||
declare function head(url: string, options?: BlobCommandOptions): Promise<HeadBlobResult | null>; | ||
declare function list(options?: ListCommandOptions): Promise<ListBlobResult>; | ||
export { BlobAccessError, BlobCommandOptions, BlobError, BlobUnknownError, HeadBlobResult, PutBlobResult, PutCommandOptions, del, head, put }; | ||
export { BlobAccessError, BlobCommandOptions, BlobError, BlobUnknownError, HeadBlobResult, ListBlobResult, ListCommandOptions, PutBlobResult, PutCommandOptions, del, head, list, put }; |
@@ -1,1 +0,1 @@ | ||
import{fetch as l}from"undici";var s=class extends Error{constructor(n){super(`Vercel Blob: ${n}`)}},a=class extends Error{constructor(){super("Vercel Blob: Access denied, please provide a valid token for this resource")}},i=class extends Error{constructor(){super("Vercel Blob: Unknown error, please contact support@vercel.com")}};async function p(e,n,t){if(!e)throw new s("pathname is required");if(!n)throw new s("body is required");if(!t||t.access!=="public")throw new s('access must be "public"');let o={authorization:`Bearer ${c(t)}`};t.contentType&&(o["x-content-type"]=t.contentType);let r=await l(`${u()}/${e}`,{method:"PUT",body:n,headers:o,duplex:"half"});if(r.status!==200)throw r.status===403?new a:new i;return r.json()}async function m(e,n){let t=await l(`${u()}/delete`,{method:"POST",headers:{authorization:`Bearer ${c(n)}`,"content-type":"application/json"},body:JSON.stringify({urls:Array.isArray(e)?e:[e]})});if(t.status!==200)throw t.status===403?new a:new i;let o=await t.json();return Array.isArray(e)?o:o[0]}async function b(e,n){let t=new URL(u());t.searchParams.set("url",e);let o=await l(t,{method:"GET",headers:{authorization:`Bearer ${c(n)}`}});if(o.status===404)return null;if(o.status!==200)throw o.status===403?new a:new i;let r=await o.json();return{...r,uploadedAt:new Date(r.uploadedAt)}}function u(){return process.env.VERCEL_BLOB_API_URL||"https://blob.vercel-storage.com"}function c(e){if(e!=null&&e.token)return e.token;if(!process.env.BLOB_READ_WRITE_TOKEN)throw new Error("BLOB_READ_WRITE_TOKEN environment variable is not set. Please set it to your write token.");return process.env.BLOB_READ_WRITE_TOKEN}export{a as BlobAccessError,s as BlobError,i as BlobUnknownError,m as del,b as head,p as put}; | ||
import{fetch as l}from"undici";var i=class extends Error{constructor(r){super(`Vercel Blob: ${r}`)}},o=class extends Error{constructor(){super("Vercel Blob: Access denied, please provide a valid token for this resource")}},a=class extends Error{constructor(){super("Vercel Blob: Unknown error, please contact support@vercel.com")}};async function m(e,r,t){if(!e)throw new i("pathname is required");if(!r)throw new i("body is required");if(!t||t.access!=="public")throw new i('access must be "public"');let s={authorization:`Bearer ${c(t)}`};t.contentType&&(s["x-content-type"]=t.contentType);let n=await l(`${u()}/${e}`,{method:"PUT",body:r,headers:s,duplex:"half"});if(n.status!==200)throw n.status===403?new o:new a;return n.json()}async function b(e,r){let t=await l(`${u()}/delete`,{method:"POST",headers:{authorization:`Bearer ${c(r)}`,"content-type":"application/json"},body:JSON.stringify({urls:Array.isArray(e)?e:[e]})});if(t.status!==200)throw t.status===403?new o:new a;let s=await t.json();return Array.isArray(e)?s:s[0]}async function p(e,r){let t=new URL(u());t.searchParams.set("url",e);let s=await l(t,{method:"GET",headers:{authorization:`Bearer ${c(r)}`}});if(s.status===404)return null;if(s.status!==200)throw s.status===403?new o:new a;let n=await s.json();return{...n,uploadedAt:new Date(n.uploadedAt)}}async function f(e){let r=new URL(u());e!=null&&e.limit&&r.searchParams.set("limit",e.limit.toString()),e!=null&&e.prefix&&r.searchParams.set("prefix",e.prefix),e!=null&&e.cursor&&r.searchParams.set("cursor",e.cursor);let t=await l(r,{method:"GET",headers:{authorization:`Bearer ${c(e)}`}});if(t.status!==200)throw t.status===403?new o:new a;let s=await t.json();return{...s,blobs:s.blobs.map(n=>({...n,uploadedAt:new Date(n.uploadedAt)}))}}function u(){return process.env.VERCEL_BLOB_API_URL||"https://blob.vercel-storage.com"}function c(e){if(e!=null&&e.token)return e.token;if(!process.env.BLOB_READ_WRITE_TOKEN)throw new Error("BLOB_READ_WRITE_TOKEN environment variable is not set. Please set it to your write token.");return process.env.BLOB_READ_WRITE_TOKEN}export{o as BlobAccessError,i as BlobError,a as BlobUnknownError,b as del,p as head,f as list,m as put}; |
{ | ||
"name": "@vercel/blob", | ||
"version": "0.6.3", | ||
"version": "0.7.0", | ||
"description": "The Vercel Blob JavaScript API client", | ||
@@ -5,0 +5,0 @@ "homepage": "https://vercel.com/blob", |
266
README.md
@@ -5,2 +5,266 @@ # 🍙 @vercel/blob | ||
See https://github.com/vercel/blob. | ||
## Install | ||
```sh | ||
npm install @vercel/blob | ||
``` | ||
## Usage | ||
```ts | ||
import * as vercelBlob from '@vercel/blob'; | ||
// usage | ||
async function someMethod() { | ||
const blob = await vercelBlob.put( | ||
'profilesv1/user-12345.txt', // pathname for the blob | ||
'Hello World!', // body | ||
{ access: 'public' }, // mandatory options | ||
); | ||
console.log(blob.url); | ||
// https://public.blob.vercel-storage.com/n1g9m63etib6gkcjqjpspsiwe7ea/profilesv1/user-12345-NoOVGDVcqSPc7VYCUAGnTzLTG2qEM2.txt | ||
} | ||
``` | ||
## API | ||
### `put(pathname, body, options)` | ||
Upload a blob to the Vercel Blob API, and returns the URL of the blob. | ||
```ts | ||
async function put( | ||
pathname: string, | ||
body: ReadableStream | String | ArrayBuffer | Blob // All fetch body types are supported: https://developer.mozilla.org/en-US/docs/Web/API/fetch#body | ||
options: { | ||
access: 'public', // mandatory, as we will provide private blobs in the future | ||
contentType?: string, // by default inferred from pathname | ||
// `token` defaults to process.env.BLOB_READ_WRITE_TOKEN on Vercel | ||
// and can be configured when you connect more stores to a project | ||
// or using Vercel Blob outside of Vercel | ||
token?: string, | ||
}): Promise<{url: string}> {} | ||
``` | ||
### del(url, options) | ||
Delete one or multiple blobs by their full URL. Returns the deleted blob(s) or null when not found. | ||
```ts | ||
async function del( | ||
url: string | string[], | ||
options?: { | ||
token?: string; | ||
}, | ||
): Promise< | ||
| { | ||
size: number; | ||
uploadedAt: Date; | ||
pathname: string; | ||
contentType: string; | ||
contentDisposition: string; | ||
contentEncoding?: string; | ||
cacheControl?: string; | ||
url: string; | ||
} | ||
| null | ||
| ({ | ||
size: number; | ||
uploadedAt: Date; | ||
pathname: string; | ||
contentType: string; | ||
contentDisposition: string; | ||
contentEncoding?: string; | ||
cacheControl?: string; | ||
url: string; | ||
} | null)[] | ||
> {} | ||
``` | ||
### head(url, options) | ||
Get the metadata of a blob by its full URL. Returns `null` when the blob does not exist. | ||
```ts | ||
async function head( | ||
url: string, | ||
options?: { | ||
token?: string; | ||
}, | ||
): Promise<{ | ||
size: number; | ||
uploadedAt: Date; | ||
pathname: string; | ||
contentType: string; | ||
contentDisposition: string; | ||
contentEncoding?: string; | ||
cacheControl?: string; | ||
url: string; | ||
} | null> {} | ||
``` | ||
### list(options) | ||
List blobs and get their metadata in the store. With an optional prefix and limit. Paginate through them. | ||
```ts | ||
async function list(options?: { | ||
token?: string; | ||
limit?: number; // defaults to 1,000 | ||
prefix?: string; | ||
cursor?: string; | ||
}): Promise<{ | ||
blobs: { | ||
size: number; | ||
uploadedAt: Date; | ||
pathname: string; | ||
contentType: string; | ||
contentDisposition: string; | ||
contentEncoding?: string; | ||
cacheControl?: string; | ||
url: string; | ||
}[]; | ||
cursor?: string; | ||
hasMore: boolean; | ||
}> {} | ||
``` | ||
## Examples | ||
- [Next.js App Router examples](./example/app/) | ||
- [https.get, axios, and got](./example/script.ts) | ||
### Next.js App Router example | ||
This example shows a form uploading a file to the Vercel Blob API. | ||
```tsx | ||
// /app/UploadForm.tsx | ||
'use client'; | ||
import type { PutBlobResult } from '@vercel/blob'; | ||
import { useState } from 'react'; | ||
export default function UploadForm() { | ||
const [blob, setBlob] = useState<PutBlobResult | null>(null); | ||
return ( | ||
<> | ||
<form | ||
action="/api/upload" | ||
method="POST" | ||
encType="multipart/form-data" | ||
onSubmit={async (event) => { | ||
event.preventDefault(); | ||
const formData = new FormData(event.currentTarget); | ||
const response = await fetch('/api/upload', { | ||
method: 'POST', | ||
body: formData, | ||
}); | ||
const blob = (await response.json()) as PutBlobResult; | ||
setBlob(blob); | ||
}} | ||
> | ||
<input type="file" name="file" /> | ||
<button type="submit">Upload</button> | ||
</form> | ||
{blob && ( | ||
<div> | ||
Blob url: <a href={blob.url}>{blob.url}</a> | ||
</div> | ||
)} | ||
</> | ||
); | ||
} | ||
``` | ||
```ts | ||
// /app/api/upload/route.ts | ||
import * as vercelBlob from '@vercel/blob'; | ||
import { NextResponse } from 'next/server'; | ||
export async function POST(request: Request) { | ||
const form = await request.formData(); | ||
const file = form.get('file') as File; | ||
if (!file) { | ||
return NextResponse.json( | ||
{ message: 'No file to upload.' }, | ||
{ status: 400 }, | ||
); | ||
} | ||
const blob = await vercelBlob.put(file.name, file, { access: 'public' }); | ||
return NextResponse.json(blob); | ||
} | ||
``` | ||
## How to list all your blobs | ||
This will paginate through all your blobs in chunks of 1,000 blobs. | ||
You can control the number of blobs in each call with `limit`. | ||
```ts | ||
let hasMore = true; | ||
let cursor: string | undefined; | ||
while (hasMore) { | ||
const listResult = await vercelBlob.list({ | ||
cursor, | ||
}); | ||
console.log(listResult); | ||
hasMore = listResult.hasMore; | ||
cursor = listResult.cursor; | ||
} | ||
``` | ||
## Error handling | ||
All methods of this module will throw if the request fails for either: | ||
- missing parameters | ||
- bad token or token doesn't have access to the resource | ||
- or in the event of unknown errors | ||
You should acknowledge that in your code by wrapping our methods in a try/catch block: | ||
```ts | ||
try { | ||
await vercelBlob.put('foo', 'bar'); | ||
} catch (error) { | ||
if (error instanceof vercelBlob.BlobAccessError) { | ||
// handle error | ||
} else { | ||
// rethrow | ||
throw error; | ||
} | ||
} | ||
``` | ||
## Releasing | ||
```sh | ||
pnpm changeset | ||
git commit -am "New version" | ||
``` | ||
Once such a commit gets merged in main, then GitHub will open a versioning PR you can merge. And the package will be automatically published to npm. | ||
## A note about Vercel file upload limitations | ||
When using Serverless or Edge Functions on Vercel, the request body size is limited to 4MB. | ||
When you want to send files larger than that to Vercel Blob, you can do so by using `@vercel/blob` from a regular Node.js script context (like at build time). This way the request body will be sent directly to Vercel Blob and not via an Edge or Serverless Function. | ||
We plan to allow sending larger files to Vercel Blob from browser contexts soon. | ||
## Running examples locally | ||
- how to run examples locally (.env.local with token) | ||
- how to run examples on Vercel (vc deploy) | ||
- how to contribute (pnpm dev to rebuild, example uses local module) | ||
- for Vercel contributors, link on how to run the API locally (edge-functions readme link, wrangler dev, pnpm dev for module) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
17957
83
270
37