r.sendecky
r.sendecky

Reputation: 10383

Haskell mongodb: Convert Binary value back to ByteString

This is something simple and stupid that I cant just see.

If a new type is defined:

newtype Binary

Constructors
Binary ByteString

Instances:
Eq Binary    
Ord Binary   
Read Binary  
Show Binary  
Typeable Binary  
Val Binary

How can I deconstruct the Binary value to get the ByteString back?

If I want to save a binary data into mongodb, say a jpg picture, I am able to construct the Val Binary type out of ByteString read from the filesystem. I then insert it into a document.

When I read the data back from the database and take it out of the document I end up with the Binary type and I am sooo stuck with it. I can not get the ByteString type back for use with ByteString.writeFile.

So skipping all the connection stuff the flow is like this:

file <- B.readFile "pic.jpg" -- reading file
let doc = ["file" =: (Binary file)] -- constructing a document to be inserted
run $ insert_ "files" doc -- insert the document
r <- run $ fetch (select [] "files") -- get Either Failure Document back from db
let d = either (error . show) (id ) r -- Get the Document out
let f  = at "file" d :: Binary -- Get the data out of the document of type Binary

Thank you.

Upvotes: 0

Views: 153

Answers (1)

kosmikus
kosmikus

Reputation: 19657

Assuming your newtype looks like this,

newtype Binary = Binary ByteString

then you can simply pattern match on the constructor to get the ByteString back:

unBinary :: Binary -> ByteString
unBinary (Binary s) = s

Upvotes: 4

Related Questions