medialit
v0.3.1
Published
MediaLit Server SDK for managing media files
Maintainers
Readme
medialit
A Node.js server-side SDK for interacting with MediaLit's API to manage media files.
Installation
npm install medialit
# or
yarn add medialit
# or
bun add medialitUsage
import { MediaLit } from "medialit";
// Initialize the client (Keep API keys on server)
const medialit = new MediaLit({
apiKey: process.env.MEDIALIT_API_KEY,
endpoint: process.env.MEDIALIT_ENDPOINT,
});
// Example usage
app.post("/api/upload", async (req, res) => {
try {
const file = req.files.file;
const media = await medialit.upload(file.path, {
access: "public",
caption: req.body.caption,
group: req.body.group,
});
res.json(media);
} catch (error) {
res.status(500).json({ error: error.message });
}
});File Input Types
The SDK accepts multiple types of file inputs:
- File Path (string)
await medialit.upload("/path/to/file.jpg");- Buffer
const buffer = Buffer.from("file content");
await medialit.upload(buffer);- Readable Stream
const stream = createReadStream("file.jpg");
await medialit.upload(stream);Configuration
The SDK can be configured using:
1. Environment Variables
MEDIALIT_API_KEY=your-api-key
MEDIALIT_ENDPOINT=https://your-medialit-instance.com # Optional, defaults to https://api.medialit.cloud2. Constructor Options
const medialit = new MediaLit({
apiKey: "your-api-key",
endpoint: "https://your-medialit-instance.com", // Optional, defaults to https://api.medialit.cloud
});
// Or simply with just the API key
const medialit = new MediaLit({
apiKey: "your-api-key",
});API Reference
new MediaLit(config?)
Pass accessToken instead of apiKey to call MediaLit with an OAuth access token, for example in a tool that logs users in.
Creates a new MediaLit instance.
Parameters:
config(optional): Configuration objectapiKey: API key for authenticationendpoint: MediaLit API endpoint URL
upload(file: FileInput, options?: UploadOptions): Promise<Media>
Uploads a file to MediaLit. Accepts file path, Buffer, or Readable stream.
Parameters:
file: A file path (string), Buffer, or Readable streamoptions(optional):access: 'public' | 'private' (default: 'private')caption: Optional caption for the mediagroup: Optional group name to organize mediafileName: Name to store. Defaults to the file name for a path, otherwisefile. Its extension sets the type.mimeType: Overrides the type found from the file name
Returns:
- Promise resolving to the uploaded media object
get(mediaId: string): Promise<Media>
Retrieves details of a specific media file.
Parameters:
mediaId: ID of the media to retrieve
Returns:
- Promise resolving to the media object
list(page?: number, limit?: number, filters?: ListFilters): Promise<Media[]>
Lists media files with pagination and filtering options.
Parameters:
page(optional): Page number (default: 1)limit(optional): Number of items per page (default: 10)filters(optional):access: Filter by 'public' or 'private' accessgroup: Filter by group name
Returns:
- Promise resolving to an array of media objects
delete(mediaId: string): Promise<void>
Deletes a media file.
Parameters:
mediaId: ID of the media to delete
getCount(): Promise<number>
Gets the total count of media files.
Returns:
- Promise resolving to the total number of media files
getStats(): Promise<MediaStats>
Gets storage statistics.
Returns:
- Promise resolving to a MediaStats object:
interface MediaStats { storage: number; // Current storage used in bytes maxStorage: number; // Maximum allowed storage in bytes }
getSettings(): Promise<MediaSettings>
Gets the current media settings.
Returns:
- Promise resolving to a MediaSettings object
updateSettings(settings: MediaSettings): Promise<void>
Updates the media settings.
Parameters:
settings: A MediaSettings object:useWebP: Whether to convert images to WebP formatwebpOutputQuality: Quality of WebP conversion (0-100)thumbnailWidth: Width of generated thumbnailsthumbnailHeight: Height of generated thumbnails
getSignature(options?: { group?: string }): Promise<string>
Creates a short-lived signature that lets a browser upload to MediaLit without your API key. Uploads made with it go into group when you pass one.
createSignatureHandler(options): (request: Request) => Promise<Response>
Creates a POST route handler that returns { signature, endpoint } for browser uploads with @medialit/react or @medialit/uploader. It works anywhere with the Fetch API Request and Response, such as Next.js route handlers, Hono, Remix, and Bun.
// app/api/medialit/signature/route.ts
import { createSignatureHandler } from "medialit";
export const POST = createSignatureHandler({
authorize: async (request) => {
const user = await getUser(request); // your app's auth
return user ? { group: user.teamId } : false;
},
});Options:
authorize(required): Returnfalseornullto refuse with 401,trueto allow, or{ group }to allow and put the uploads in a group. Anyone who passes this check can upload to your MediaLit app.apiKey,endpoint(optional): Same as the constructor. They are read when the first request arrives.client(optional): An existingMediaLitclient to use instead.publicEndpoint(optional): The MediaLit URL the browser should use when it differs from the one your server uses, for example inside Docker.
Media Object Structure
The Media object returned by the API includes:
interface Media {
mediaId: string;
fileName: string;
originalFileName: string;
mimeType: string;
size: number;
thumbnailGenerated: boolean;
accessControl: "private" | "public";
group?: string;
caption?: string;
}Type Definitions
interface UploadOptions {
group?: string;
access?: "private" | "public";
caption?: string;
}
interface MediaStats {
storage: number;
maxStorage: number;
}
interface MediaSettings {
useWebP?: boolean;
webpOutputQuality?: number;
thumbnailWidth?: number;
thumbnailHeight?: number;
}Error Handling
The SDK implements consistent error handling:
Environment Check:
- Throws error if initialized in a browser environment
- Error message: "MediaLit SDK is only meant to be used in a server-side Node.js environment"
API Key Validation:
- Throws error if API key is missing
- Error message: "API Key is required"
File Input Validation:
- Throws error for invalid file inputs
- Error message: "Invalid file input. Must be a file path, Buffer, or Readable stream"
Example:
try {
const media = await medialit.upload(file);
} catch (error) {
if (error.message.includes("server-side Node.js environment")) {
console.error("SDK cannot be used in browser environment");
} else if (error.message === "API Key is required") {
console.error("Missing API key configuration");
} else {
console.error("Operation failed:", error.message);
}
}Development
Running Tests
bun run testTypeScript Support
This package includes TypeScript type definitions. No additional type packages are required.
Requirements
- Node.js >= 18.0.0
Contributing
Please refer to the main MediaLit repository's contributing guidelines.
License
MIT License
