Skip to content

Commit

Permalink
feat: Add BSON interfaces to help enhance type safety of low level code
Browse files Browse the repository at this point in the history
  • Loading branch information
notheotherben committed Dec 15, 2015
1 parent 399babc commit 67872f2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
24 changes: 24 additions & 0 deletions lib/BSON.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Various interfaces for low level BSON types used within Iridium.
*/

/**
* Represents a low level BSON value with its included _bsontype property.
*/
export interface Value {
_bsontype: string;
}

/**
* Represents a raw ObjectID object received from the database.
*/
export interface ObjectID extends Value {
id: string;
}

/**
* Represents a raw Binary object received from the database.
*/
export interface Binary extends Value {
buffer: Buffer;
}
15 changes: 8 additions & 7 deletions lib/Transforms.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import MongoDB = require('mongodb');
import {Model} from './Model';
import * as BSON from './BSON';

export interface Transforms<TDocument> {
/**
* A transform which is applied to the entire document.
*/
$document?: PropertyTransform<TDocument>;
$document?: PropertyTransform<any>;
[property:string]: PropertyTransform<any>;
}

Expand Down Expand Up @@ -35,15 +36,15 @@ export interface PropertyTransform<T> {
}

export const DefaultTransforms = {
ObjectID: <PropertyTransform>{
fromDB: value => value && value._bsontype == 'ObjectID' ? new MongoDB.ObjectID(value.id).toHexString() : value,
toDB: value => value && typeof value === 'string' ? new MongoDB.ObjectID(value) : value
ObjectID: <PropertyTransform<MongoDB.ObjectID | BSON.ObjectID>>{
fromDB: value => value && (<BSON.ObjectID>value)._bsontype == 'ObjectID' ? new MongoDB.ObjectID((<BSON.ObjectID>value).id).toHexString() : value,
toDB: value => typeof value === 'string' ? new MongoDB.ObjectID(value) : value
},
Binary: <PropertyTransform>{
Binary: <PropertyTransform<MongoDB.Binary | BSON.Binary>>{
fromDB: value => {
if(!value) return null;
if(value._bsontype === "Binary")
return value.buffer;
if((<BSON.Binary>value)._bsontype === "Binary")
return (<BSON.Binary>value).buffer;

return value;
},
Expand Down

0 comments on commit 67872f2

Please sign in to comment.