Skip to content

Instantly share code, notes, and snippets.

@bwaterschoot
Created December 9, 2014 16:15
Show Gist options
  • Save bwaterschoot/9bfe05082c324cec692a to your computer and use it in GitHub Desktop.
Save bwaterschoot/9bfe05082c324cec692a to your computer and use it in GitHub Desktop.
Wrapper around Azure blob storage
module AzureBlobStorage
open System.IO
open Microsoft.WindowsAzure.Storage
open Microsoft.WindowsAzure
open Microsoft.WindowsAzure.Storage.Blob
type Time = | Seconds of int
type Cacheable =
| Yes of Time
| No
type ContentType =
| Json
| Xml
| Txt
type StorageItem<'a> = {
ContentType: ContentType
Cacheable : Cacheable
Content: 'a
}
let setCacheControl (cacheableItem: Cacheable) (blockBlob:CloudBlockBlob) =
match cacheableItem with
| Yes time ->
let (Seconds seconds) = time
blockBlob.Properties.CacheControl <- sprintf "public, max-age=%i" seconds
blockBlob
| No -> blockBlob
let setContentType (contentType: ContentType) (blockBlob:CloudBlockBlob) =
let contentTypeText =
match contentType with
| Json -> "application/json"
| Xml -> "application/xml"
| Txt -> "text/plain"
blockBlob.Properties.ContentType <- contentTypeText
blockBlob
let private getContainer (client:CloudBlobClient) (containerName: string) =
client.GetContainerReference(containerName)
let private awaitTask (t: System.Threading.Tasks.Task) = t |> Async.AwaitIAsyncResult |> Async.Ignore
let private uploadBlobAsync item (blockBlob:CloudBlockBlob) =
async {
match box item with
| :? Stream as s -> do! awaitTask (blockBlob.UploadFromStreamAsync s)
| :? string as text -> do! awaitTask (blockBlob.UploadTextAsync text)
| _ -> return failwith "This type is not supported"
}
let uploadBlobToContainerAsync<'a> (clientFactory: unit-> CloudBlobClient) (container:string) (blobName:string) (item: StorageItem<'a>) =
async {
let container = getContainer (clientFactory()) container
let blockBlob = container.GetBlockBlobReference(blobName)
do! blockBlob
|> setCacheControl item.Cacheable
|> setContentType item.ContentType
|> uploadBlobAsync item.Content
return blockBlob
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment