1- // GridStoreAdapter
2- //
3- // Stores files in Mongo using GridStore
4- // Requires the database adapter to be based on mongoclient
1+ /**
2+ GridStoreAdapter
3+ Stores files in Mongo using GridStore
4+ Requires the database adapter to be based on mongoclient
55
6- import { GridStore } from 'mongodb' ;
6+ @flow weak
7+ */
8+
9+ import { MongoClient , GridStore , Db } from 'mongodb' ;
710import { FilesAdapter } from './FilesAdapter' ;
811
912export class GridStoreAdapter extends FilesAdapter {
13+ _databaseURI : string ;
14+ _connectionPromise : Promise < Db > ;
15+
16+ constructor ( mongoDatabaseURI : string ) {
17+ super ( ) ;
18+ this . _databaseURI = mongoDatabaseURI ;
19+ this . _connect ( ) ;
20+ }
21+
22+ _connect ( ) {
23+ if ( ! this . _connectionPromise ) {
24+ this . _connectionPromise = MongoClient . connect ( this . _databaseURI ) ;
25+ }
26+ return this . _connectionPromise ;
27+ }
28+
1029 // For a given config object, filename, and data, store a file
1130 // Returns a promise
12- createFile ( config , filename , data ) {
13- return config . database . connect ( ) . then ( ( ) => {
14- let gridStore = new GridStore ( config . database . adapter . database , filename , 'w' ) ;
31+ createFile ( config , filename : string , data ) {
32+ return this . _connect ( ) . then ( database => {
33+ let gridStore = new GridStore ( database , filename , 'w' ) ;
1534 return gridStore . open ( ) ;
16- } ) . then ( ( gridStore ) => {
35+ } ) . then ( gridStore => {
1736 return gridStore . write ( data ) ;
18- } ) . then ( ( gridStore ) => {
37+ } ) . then ( gridStore => {
1938 return gridStore . close ( ) ;
2039 } ) ;
2140 }
2241
23- deleteFile ( config , filename ) {
24- return config . database . connect ( ) . then ( ( ) => {
25- let gridStore = new GridStore ( config . database . adapter . database , filename , 'w' ) ;
42+ deleteFile ( config , filename : string ) {
43+ return this . _connect ( ) . then ( database => {
44+ let gridStore = new GridStore ( database , filename , 'w' ) ;
2645 return gridStore . open ( ) ;
2746 } ) . then ( ( gridStore ) => {
2847 return gridStore . unlink ( ) ;
@@ -31,13 +50,14 @@ export class GridStoreAdapter extends FilesAdapter {
3150 } ) ;
3251 }
3352
34- getFileData ( config , filename ) {
35- return config . database . connect ( ) . then ( ( ) => {
36- return GridStore . exist ( config . database . adapter . database , filename ) ;
37- } ) . then ( ( ) => {
38- let gridStore = new GridStore ( config . database . adapter . database , filename , 'r' ) ;
39- return gridStore . open ( ) ;
40- } ) . then ( ( gridStore ) => {
53+ getFileData ( config , filename : string ) {
54+ return this . _connect ( ) . then ( database => {
55+ return GridStore . exist ( database , filename )
56+ . then ( ( ) => {
57+ let gridStore = new GridStore ( database , filename , 'r' ) ;
58+ return gridStore . open ( ) ;
59+ } ) ;
60+ } ) . then ( gridStore => {
4161 return gridStore . read ( ) ;
4262 } ) ;
4363 }
0 commit comments