Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(azure-storage): added the ability to access the underlying BlobServiceClient #311

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ npm-debug.log

# source
dist
blob

# schematics
schematics/install/*.js
Expand Down
69 changes: 66 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,9 @@ Learn how to get started with [Azure table storage for NestJS](https://trilon.io
## Before Installation

1. Create a Storage account and resource ([read more](http://bit.ly/nest_new-azure-storage-account))
1. In the [Azure Portal](https://portal.azure.com), go to **Dashboard > Storage > _your-storage-account_**.
2. Note down the "AccountName", "AccountKey" obtained at **Access keys** and "AccountSAS" from **Shared access signature** under **Settings** tab.
2. In the [Azure Portal](https://portal.azure.com), go to **Dashboard > Storage > _your-storage-account_**.
3. Note down the "AccountName", "AccountKey" obtained at **Access keys** and "AccountSAS" from **Shared access signature** under **Settings** tab.
4. (Optional) Install the [azurite](https://www.npmjs.com/package/azurite) package to setup a development environment.

## (Recommended) Installation and automatic configuration

Expand All @@ -63,9 +64,11 @@ Other available flags:
- `rootModuleClassName` - the name of the root module class, default: `AppModule`
- `mainFileName` - Application main file, default: `main`
- `skipInstall` - skip installing dependencies, default: `false`
- `serviceUrlProvider` - override the default service url provider (which is pointing to `https://${options.accountName}.blob.core.windows.net/?${options.sasKey}`)
- `storageAccountName` (required) - The Azure Storage account name (see: http://bit.ly/azure-storage-account)
- `storageAccountSAS` (required) - The Azure Storage SAS Key (see: http://bit.ly/azure-storage-sas-key).


## (Option 2) Manual configuration

1. Install the package using NPM:
Expand Down Expand Up @@ -140,7 +143,7 @@ export class AppModule {}

> You may provide a default `containerName` name for the whole module, this will apply to all controllers withing this module. You can also provide (override) the `containerName` in the controller, for each route.

## Story examples
## Storage examples

### Store a file using the default container name

Expand Down Expand Up @@ -245,6 +248,66 @@ export class AppController {
}
```

### Download a file from the originalname

```typescript
import { AzureStorageService } from '@nestjs/azure-storage';
import { Injectable } from '@nestjs/common';

@Injectable()
export class TestService {
constructor(
readonly storage: AzureStorageService
) {
storage.getContainerClient().getBlobClient(file.originalname).downloadToBuffer().then(buffer => {
buffer.toString() // content of foo-bar.txt
});
}
}
```

## Development
You can setup a **development environment** using the default configuration from [azurite](https://www.npmjs.com/package/azurite).
This example also shows you how to use the library with a AccountKEY instead of SAS configuration, this is **not recommended for production**.
```typescript
import {
SASProtocol,
StorageSharedKeyCredential,
generateAccountSASQueryParameters,
AccountSASResourceTypes,
AccountSASServices,
AccountSASPermissions
} from "@azure/storage-blob";
import {Module} from "@nestjs/common";
import {AzureStorageModule} from "@nestjs/azure-storage";

@Module({
imports: [
AzureStorageModule.withConfig({
containerName: "container",
accountName: "devstoreaccount1",
serviceUrlProvider: (options) => {
return `http://127.0.0.1:10000/${options.accountName}/?${options.sasKey}`
},
sasKey: generateAccountSASQueryParameters({
resourceTypes: AccountSASResourceTypes.parse("sco").toString(),
services: AccountSASServices.parse("b").toString(),
permissions: AccountSASPermissions.parse("racwdl"),
startsOn: new Date(Date.now() - 86400),
expiresOn: new Date(Date.now() + 86400),
protocol: SASProtocol.HttpsAndHttp
}, new StorageSharedKeyCredential(...Object.values({
accountName: 'devstoreaccount1',
accountKey: 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=='
}) as [string, string])).toString(),
})
]
})
export class AppModule {

}
```

## Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
Expand Down
42 changes: 42 additions & 0 deletions fulltest/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {NestFactory} from "@nestjs/core";
import {AppModule} from "./module";
import {AzureStorageService, UploadedFileMetadata} from "../lib";
import {readdir} from "fs";
import {join} from "path";

const buffer = Buffer.from('test');
const file: UploadedFileMetadata = {
buffer,
fieldname: 'file',
originalname: 'test.txt',
encoding: 'utf-8',
mimetype: 'text/plain',
size: buffer.length + '',
storageUrl: null,
};

async function main() {
const app = await NestFactory.createApplicationContext(AppModule);
await app.init();
const storage = await app.select(AppModule).get(AzureStorageService);
await storage.upload(file);
const files = await new Promise<string[]>((resolve, reject) => readdir(
join(__dirname, '..', 'blob', "__blobstorage__"),
(err, result) => err ? reject(err) : resolve(result)
));
if(files.length === 0) {
throw new Error("No file has been stored.");
}
const result = await storage.getContainerClient().getBlobClient(file.originalname).downloadToBuffer();
if(result.toString() !== "test") {
throw new Error("Blob content changed during upload.");
}
}

main().then(() => {
console.log("Function Test Finished Successfully");
}).catch((err) => {
console.error(err);
console.log("Function Test failed");
process.exit(1);
})
36 changes: 36 additions & 0 deletions fulltest/module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {
SASProtocol,
StorageSharedKeyCredential,
generateAccountSASQueryParameters,
AccountSASResourceTypes,
AccountSASServices,
AccountSASPermissions
} from "@azure/storage-blob";
import {Module} from "@nestjs/common";
import {AzureStorageModule} from "../lib";

@Module({
imports: [
AzureStorageModule.withConfig({
containerName: "container",
accountName: "devstoreaccount1",
serviceUrlProvider: (options) => {
return `http://127.0.0.1:10000/${options.accountName}/?${options.sasKey}`
},
sasKey: generateAccountSASQueryParameters({
resourceTypes: AccountSASResourceTypes.parse("sco").toString(),
services: AccountSASServices.parse("b").toString(),
permissions: AccountSASPermissions.parse("racwdl"),
startsOn: new Date(Date.now() - 86400),
expiresOn: new Date(Date.now() + 86400),
protocol: SASProtocol.HttpsAndHttp
}, new StorageSharedKeyCredential(...Object.values({
accountName: 'devstoreaccount1',
accountKey: 'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw=='
}) as [string, string])).toString(),
})
]
})
export class AppModule {

}
Loading