uploader3-connector
Uploader3 Connector is a connector for Uploader3. Currently, it only supports NFT.storage (opens in a new tab) IPFS service provider.
Supported service provider
💡
Support Img3 and list here? Contact @muxin (opens in a new tab) or create a ticket in LXDAO DC (opens in a new tab).
Usage
import { createConnector } from '@lxdao/uploader3-connector';
API
createConnector
Create a connector for Uploader3 upload service.
export const createConnector: (service: 'NFT.storage' | 'lighthouse', options: { token: string }) => Connector;
Types reference
Connector
interface PostImageFile {
/** base64 encoded image file */
data: string;
/** file type */
type: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/jpg';
}
export type Connector = {
postImage: (image: PostImageFile) => Promise<{ cid: string; url: string }>;
};
Examples
Use with Uploader3
App.txs
import { createConnector } from '@lxdao/uploader3-connector';
import { Uploader3 } from '@lxdao/uploader3';
export default function App() {
const connector = createConnector('NFT.storage', {
token: 'YOUR_TOKEN',
});
return <Uploader3 connector={connector}>{'...'}</Uploader3>;
}
⚠️
Please do not use the token directly in the code. Make sure you use it in a secure environment, such as an internal network.
Use with Next.js api routes
You can refer to the following code to install uploader3-connector on other servers. This is the way we recommend.
pages/api/upload.ts
import type { NextApiRequest, NextApiResponse } from 'next';
import { createConnector, type Uploader3Connector } from '@lxdao/uploader3-connector';
//Provided `NFT_TOKEN` in environment variables
const connector = createConnector('NFT.storage', { token: process.env.NFT_TOKEN! });
export default async (req: NextApiRequest, res: NextApiResponse) => {
const reqBody = <Uploader3Connector.PostImageFile>req.body;
let { data: imageData = '', type } = reqBody;
if (!imageData) {
res.status(400).json({ error: 'No image data' });
return;
}
if (!type) {
res.status(400).json({ error: 'No image type' });
return;
}
if (imageData.startsWith('data:image/')) {
imageData = imageData.replace(/^data:image\/\w+;base64,/, '');
}
const buffer = Buffer.from(imageData, 'base64');
// if buffer size > 2MB throw error
// or other your own logic
if (buffer.byteLength > 2 * 1024 * 1024) {
res.status(500).json({ error: 'file size > 2MB' });
return;
}
const result = await connector.postImage({ data: imageData, type }).catch((e) => {
res.status(500).json({ error: e.message });
});
if (result) {
res.status(200).json({ url: result.url });
}
};