npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-storage-blob

v2.1.0

Published

Azure Blob Storage module for Nest.js

Downloads

62

Readme

nestjs-storage-blob

Azure Blob Storage module for Nest.js

Introduction

  • Nest.js with @azure/storage-blob

  • @nestjs/azure-storage

    • does not provide the method to upload a file using presigned url
    • does not provide multiple authentication methods
    • does not provide method to upload files directly to Azure without passing through my server

Usage

Setup

  • Install packages
npm install nestjs-storage-blob @azure/storage-blob
  • Set environment variables(.env)
# required
NEST_STORAGE_BLOB_CONNECTION="DefaultEndpointsProtocol=https;AccountName=<ACCOUNT_NAME>;AccountKey=<ACCOUNT_KEY>;EndpointSuffix=core.windows.net"

# optional
NEST_STORAGE_BLOB_CONTAINER="<CONTAINER_NAME>"

Option 1

// app.module.ts

import { Module } from '@nestjs/common';
import { StorageBlobModule } from 'nestjs-storage-blob';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    StorageBlobModule.forRoot({
      connection: process.env.NEST_STORAGE_BLOB_CONNECTION,
      isGlobal: true, // optional
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Option 2

// app.module.ts

import { Module } from '@nestjs/common';
import { StorageBlobModule } from 'nestjs-storage-blob';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [
    StorageBlobModule.forRootAsync({
      useFactory: () => ({
        connection: process.env.NEST_STORAGE_BLOB_CONNECTION,
      }),
      isGlobal: true, // optional
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Usage

// app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { StorageBlobService } from 'nestjs-storage-blob';

@Controller()
export class AppController {
  constructor(private readonly storageBlobService: StorageBlobService) {}

  @Get('/')
  async getSas() {
    const containerName = 'mycontainer';
    const fileName = 'test.txt';
    const expiresOn = new Date(new Date().getTime() + 1000 * 60 * 60 * 24);

    const accountSasUrl = await this.storageBlobService.getAccountSasUrl();

    const containerSasUrl = await this.storageBlobService.getContainerSasUrl(containerName);

    const blobSasUrl = await this.storageBlobService.getBlockBlobSasUrl(
      containerName,
      fileName,
      { add: true, create: true, read: true, delete: true },
      { expiresOn },
    );

    return { accountSasUrl, containerSasUrl, blobSasUrl };
  }
}
// Example 1. Upload file from server-side

// Get Blob SAS URL which will be endpoint of uploading file
const res = await axios.get('https://<YOUR_SERVER>/block-blob-sas');
const blobSasUrl = res.data.blobSasUrl;

// Upload a file directly to Azure Blob Storage which reduces the load on the server
const buffer = fs.readFileSync(path.join(process.cwd(), 'myimage.jpg'));

if (buffer) {
  await axios
    // Do not use `FormData`
    .put(blobSasUrl, buffer, {
      headers: {
        // Do not forget to set headers
        'x-ms-blob-type': 'BlockBlob',
      },
    })
    .then((res) => {
      // 201 Created
      console.log(res.status);
    })
    .catch((err: any) => {
      console.error(err.message);
    });
}
// Example 2. Upload file from browser-side

const onChange: ChangeEventHandler<HTMLInputElement> = async (ev) => {
  const file = ev.file;

  // Get Blob SAS URL which will be endpoint of uploading file
  const res = await axios.get('https://<YOUR_SERVER>/block-blob-sas');
  const blobSasUrl = res.data.blobSasUrl;

  axios
    // Do not use `FormData`
    .put(blobSasUrl, file, {
      headers: {
        // Do not forget to set headers
        'x-ms-blob-type': 'BlockBlob',
      },
    })
    .then((res) => {
      // 201 Created
      console.log(res.status);
    })
    .catch((err: any) => {
      console.error(err.message);
    });
};

Contribution

Install

# to test locally
pnpm add link:./path/to/nestjs-storage-blob

Publish

# 2FA error occurs when using yarn on Windows machine
pnpm release

Test

# set environment variable at `./example/.env.test`
NEST_STORAGE_BLOB_CONNECTION="DefaultEndpointsProtocol=https;AccountName=<ACCOUNT_NAME>;AccountKey=<ACCOUNT_KEY>;EndpointSuffix=core.windows.net"
NEST_STORAGE_BLOB_CONTAINER="<CONTAINER_NAME>"

nestjs-storage-blob