Code Monkey home page Code Monkey logo

bunnycdn's Introduction

Documentation

Overview

This project consists of several modules:

  1. Types and Definitions: Defining ErrorResponse, StatusResponse, Video related types and other types, and utility types.
  2. EdgeStorage.ts: Provides functionality for interacting with BunnyCDN storage endpoints.
  3. Collection.ts: Represents a video collection in Bunny Stream and provides functions for modifying the collection.
  4. Stream.ts: Provides the main functionalities and interacts with Bunny Stream API's - Video and Collection management operations.

Quick Start

Global

import BunnyCDN, { StorageEndpoints } from "bunnycdn";

const cdn = new BunnyCDN({
    AccessKey: "access-key",
    StorageZone: StorageEndpoints.Falkenstein
});

Spesific

EdgeStorage
import { EdgeStorage, StorageEndpoints } from "bunnycdn";

const edgeStorage = new EdgeStorage("access-key", StorageEndpoints.Falkenstein);
const storageZone = edgeStorage.CreateClient("storage-zone-name");
const files = await storageZone.ListFiles('.')
for (let file of files) {
    console.log(`A file was found with the name ${file.ObjectName} and the guid ${file.Guid} with ${file.Length} bytes.`)
}
Stream
import { Stream } from "bunnycdn";

const stream = new Stream();
const library = stream.GetLibrary(1234, 'access-key');
const MyCollection = await library.GetCollection("collection-guid");

const result = (
    await library.ListVideos({
        collection: MyCollection.data?.collectionId,
        page: 1,
        itemsPerPage: 100,
        orderBy: 'date',
        search: 'My Video'
    })
).data || {};

console.log(
    result.itemsPerPage,
    result.currentPage,
    result.totalItems,
);

for (let video of result) {
    console.log(`${video.title}} has ${video.views} views and is ${video.length} seconds long`);
}

Types and Definitions

ErrorResponse

Type: interface

interface ErrorResponse {
    HttpCode: number;
    Message: string;
}
  • Represents an error response object with the properties HttpCode and Message.

StatusResponse

Type: enum

enum StatusResponse {
    OK = 200,
    CREATED = 201,

    BAD_REQUEST = 400,
    UNAUTHORIZED = 401,
    NOT_FOUND = 404,

    INTERNAL_SERVER_ERROR = 500,

    // Undefined
    UNDEFINED = 0
}
  • Represents the possible HTTP status code responses.

Video related types

Declares VideoCaption, VideoChapter, VideoMoment, VideoMetaTag, VideoTranscodingMessageLevel, VideoTranscodingMessage, VideoStatus, Video, APIVideo, VideoStatics, and VideoList.

Please refer to the provided typings for their definitions.

EdgeStorage.ts

Class: EdgeStorage

To create an instance of EdgeStorage, you need to provide AccessKey and optionally, StorageZone as parameters.

Example:

const edgeStorage = new EdgeStorage('your-access-key', StorageEndpoints.Falkenstein);

Methods:

  • get Endpoint(): Returns the current storage endpoint being used.
      edgeStorage.Endpoint
  • set Endpoint(StorageZone: StorageEndpoints): Sets the current storage endpoint.
      edgeStorage.Endpoint = StorageEndpoints.NY
  • get AccessKey(): Returns the access key being used.
      edgeStorage.AccessKey
  • set AccessKey(AccessKey: string): Sets the access key.
      edgeStorage.AccessKey = 'access-key-2'
  • CreateClient(StorageZoneName: string): Creates and returns an instance of EdgeStorageClient.
      edgeStorage.CreateClient('storage-zone-name')

Class: EdgeStorageClient

Extends from EdgeStorage.

Methods:

  • ListFiles(path: string): Fetches and returns a list of storage entities for the given path.
      await edgeStorageClient.ListFiles('.')
  • DownloadFile(path: string): Downloads the file at the given path.
      await edgeStorageClient.DownloadFile('videos/hello_world.mp4')
  • UploadFile(path: string, fileContent: Buffer): Uploads a file with the specified content to the given path.
      await edgeStorageClient.UploadFile('images/javascript.png', MyImageBuffer)
  • DeleteFile(path: string): Deletes a file at the given path.
      await edgeStorageClient.DeleteFile('temp/old_database.json')

Collection.ts

Interface: APICollection

interface APICollection {
    videoLibraryId: number;
    guid?: string;
    name?: string;
    videoCount: number;
    totalSize: number;
    previewVideoIds?: string;
}
  • Represents the API response for a video collection.

Class: Collection

This class represents a video collection with methods to update and delete itself.

Constructor parameters:

  • data: APICollection
  • collectionId: string
  • library: Library

Methods:

  • Update(name?: string): Updates the collection with the new name if provided.
      await myCollection.Update('my-collection-updated')
  • Delete(): Deletes the collection.
      await myCollection.Delete()

Stream.ts

Class: Stream

Main class for working with Bunny Stream APIs.

Constructor:

const stream = new Stream();

Methods:

  • GetLibrary(libraryId: number, accessKey: string): Retrieves the library with the given library ID and access key.

Class: Library

This class represents a Bunny Stream library.

Constructor parameters:

  • libraryId: number
  • accessKey: string

Methods:

  • GetVideo(videoId: number): Retrieves a video with the given video ID.
      await stream.GetVideo(12345)
  • GetVideoStatistics(params: object): Fetches video statistics based on given parameters.
      await stream.GetVideoStatistics({
          dateFrom: '2023-01-01T12:00:00.000Z',
          dateTo: '2023-04-03T12:00:00.000Z',
          hourly: true,
          videoGuid: 'my-unique-guid'
      })
  • ListVideos(params: object): Lists videos in the library based on given parameters.
      await stream.ListVideos({
          page: 1;
          itemsPerPage: 100;
          search: 'My video';
          collection: 'my-collection-guid',
          orderBy: 'date'
      })
  • CreateVideo(params: object): Creates a new video in the library.
      await stream.CreateVideo({
          title: 'My Newest Video',
          collectionId: 'my-collection-guid',
          thumbnailTime: 67 // hours * 3600 + minutes * 60 + seconds
      })
  • FetchVideo(bodyParams: object, queryParams: object): Fetches a video from a remote URL.
      await stream.FetchVideo({
          url: 'https://example.com/my-video-link',
          headers: {
              'my-header-key': 'my-header-value',
              // ...
          }
      }, {
          collectionId: 'my-collection-guid',
          lowPriority: true,
          thumbnailTime: 67 // hours * 3600 + minutes * 60 + seconds
      })
  • GetCollection(collectionId: string): Retrieves a collection with the given collection ID.
      await stream.GetCollection('my-collection-guid')
  • GetCollectionList(queryParams: object): Retrieves a list of collections based on given parameters.
      await stream.GetCollection({
          page: 1,
          itemsPerPage: 100,
          search: 'My Collection',
          orderBy: "date"
      })
  • CreateCollection(name?: string): Creates a new collection in the library with the specified name.
      await stream.CreateCollection('my-collection')

Video.ts

Interface: UpdateParams

export interface UpdateParams {
    title?: string;
    collectionId?: string;
    chapters?: VideoChapter[];
    moments?: VideoMoment[];
    metaTags?: VideoMetaTag[];
}
  • Represents the parameters that can be updated when calling the Update method.

Class: Video

This class encapsulates a video in Bunny Stream.

Constructor parameters:

  • library: Library
  • data: APIVideo
  • videoId: number

Methods:

  • Update(props: UpdateParams): Updates the video with the provided properties. Give a object whose is suitable for UpdateParams
  • Delete(): Deletes the video.
      await video.Delete()
  • Upload(enabledResolutions?: string): Uploads the video with the specified resolutions (optional). Coming Soon
  • GetHeatmap(): Retrieves the video heatmap data.
      await video.GetHeatmap()
  • Reencode(): Re-encodes the video.
      await video.Reencode()
  • SetThumbnail(payload: { thumbnailUrl?: string; }): Sets the thumbnail of the video.
      await video.SetThumbnail({ 
          thumbnailUrl: 'https://example.com/my-thumbnail.png'
      })
  • AddCaption(srclang: string, params: { srclang?: string; label?: string; captionsFile?: string; }): Adds a caption to the video.
      await video.AddCaption('tr', {
          srclang: 'tr',
          label: 'Turkish',
          captionsFile: Base64(MyFileContent)
      })
  • DeleteCaption(srclang: string): Deletes a caption from the video.
      await video.DeleteCaption('tr')

By using the Video class, you can manage individual videos in your Bunny Stream library.

By using these classes and methods, you can perform various operations related to BunnyCDN Storage and Bunny Stream.

bunnycdn's People

Contributors

wraith4081 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

chikanz

bunnycdn's Issues

Transition Phase from Old Version to New Version

The existing 1.x.x versions were made temporary. I have started working on the main version, v2.x.x. I will complete it in time and release it as the main version

To-Do List

Bunny.net API

  • Countries
  • API Keys
  • Region
  • Stream Video Library
  • DNS Zone
  • Countries
  • Pull Zone
  • Purge
  • Statistics
  • Storage Zone

Edge Storage API

  • Manage Files
  • Browse Files

Stream API

  • Manage Collections
  • Manage Videos

Bug in dowload file funtion

Hello,

I was trying to dowload a file but it keeps failing, it seems you trying to convert the file to json in this line.

we should convert the response to blob

const body = await request.then(res => res.json());

best Regards
Omar

ESM error

Please forgive my ignorance, but I'm running into problems trying to use this, and I'm not sure whether I'm doing something wrong or this is a bug.

Sample code:

import { EdgeStorage, StorageEndpoints } from 'bunnycdn';
const edgeStorage = new EdgeStorage(
	'REDACTED',
	StorageEndpoints.Falkenstein // This is my correct endpoint
);

const storageZone = edgeStorage.CreateClient('MY_STORAGE');

export default async function run(url: string) {
	const files = await storageZone.ListFiles('.');
	for (let file of files) {
		console.log(
			`A file was found with the name ${file.ObjectName} and the guid ${file.Guid} with ${file.Length} bytes.`
		);
	}

}

run();

Running this gives me the error:

PROJECT_FOLDER/node_modules/ts-node/dist/index.js:851
            return old(m, filename);
                   ^
Error [ERR_REQUIRE_ESM]: require() of ES Module PROJECT_FOLDER/node_modules/node-fetch/src/index.js from PROJECT_FOLDER/node_modules/bunnycdn/dist/EdgeStorage.js not supported.
Instead change the require of index.js in PROJECT_FOLDER/node_modules/bunnycdn/dist/EdgeStorage.js to a dynamic import() which is available in all CommonJS modules.
    at require.extensions.<computed> [as .js] (PROJECT_FOLDER/node_modules/ts-node/dist/index.js:851:20)
    at Object.<anonymous> (PROJECT_FOLDER/node_modules/bunnycdn/dist/EdgeStorage.js:16:38)
    at require.extensions.<computed> [as .js] (PROJECT_FOLDER/node_modules/ts-node/dist/index.js:851:20)
    at Object.<anonymous> (PROJECT_FOLDER/node_modules/bunnycdn/dist/index.js:7:39)
    at require.extensions.<computed> [as .js] (PROJECT_FOLDER/node_modules/ts-node/dist/index.js:851:20)
    at Object.<anonymous> (PROJECT_FOLDER/src/helpers/downloadImage.ts:12:20)
    at m._compile (PROJECT_FOLDER/node_modules/ts-node/dist/index.js:857:29)
    at require.extensions.<computed> [as .ts] (PROJECT_FOLDER/node_modules/ts-node/dist/index.js:859:16)
    at phase4 (PROJECT_FOLDER/node_modules/ts-node/dist/bin.js:466:20)
    at bootstrap (PROJECT_FOLDER/node_modules/ts-node/dist/bin.js:54:12)
    at main (PROJECT_FOLDER/node_modules/ts-node/dist/bin.js:33:12)
    at Object.<anonymous> (PROJECT_FOLDER/node_modules/ts-node/dist/bin.js:579:5) {
  code: 'ERR_REQUIRE_ESM'
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.