1
+ var BaseProvider = require ( './BaseProvider' ) ;
2
+ var CacheProvider = require ( './CacheProvider' ) ;
3
+ var util = require ( 'util' ) ;
4
+
5
+ var DefaultDatabaseAdapter = require ( '../ExportAdapter' ) ;
6
+ var defaultURI = "mongodb://localhost:27017/parse" ;
7
+
8
+ function DatabaseProvider ( adapter ) {
9
+ DatabaseProvider . super_ . call ( this )
10
+ } ;
11
+
12
+ function setup ( config ) {
13
+ config = config || { } ;
14
+ config . adapter = config . adapter || DefaultDatabaseAdapter ;
15
+ this . dbConnections = config . dbConnections || this . dbConnections || { } ;
16
+ this . databaseURI = config . defaultURI || defaultURI ;
17
+ this . appDatabaseURIs = config . appDatabaseURIs || { } ;
18
+
19
+ var adapter = this . resolveAdapter ( config . adapter , config . options ) ;
20
+ this . setAdapter ( adapter ) ;
21
+ }
22
+
23
+ // TODO: Reimplement this whenever @Flovilmart finishes running CloudCode in subprocesses
24
+ function registerAppDatabaseURI ( appId , uri ) {
25
+ this . appDatabaseURIs [ appId ] = uri ;
26
+ }
27
+
28
+ function getDatabaseConnections ( ) {
29
+ return this . dbConnections ;
30
+ }
31
+
32
+ function getDatabaseConnection ( appId ) {
33
+ if ( this . dbConnections [ appId ] ) {
34
+ return this . dbConnections [ appId ] ;
35
+ }
36
+
37
+ var cache = CacheProvider . getAdapter ( ) ;
38
+ var app = cache . get ( appId ) ;
39
+
40
+ if ( ! app ) {
41
+ throw new Error ( 'Application ID provided is not a registered application.' ) ;
42
+ }
43
+
44
+ var adapterFn = this . getAdapter ( ) ;
45
+ var dbURI = this . appDatabaseURIs [ appId ] || this . databaseURI ;
46
+ var options = { collectionPrefix : app . collectionPrefix } ;
47
+
48
+ this . dbConnections [ appId ] = new adapterFn ( dbURI , options ) ;
49
+ this . dbConnections [ appId ] . connect ( ) ;
50
+ return this . dbConnections [ appId ] ;
51
+ }
52
+
53
+ // Overriding resolveAdapter to return the class, rather than an instance
54
+ function resolveAdapter ( adapter , options ) {
55
+ // Support passing in adapter paths
56
+ if ( typeof adapter === 'string' ) {
57
+ adapter = require ( adapter ) ;
58
+ }
59
+
60
+ return adapter ;
61
+ }
62
+
63
+ util . inherits ( DatabaseProvider , BaseProvider ) ;
64
+
65
+ DatabaseProvider . prototype . setup = setup ;
66
+ DatabaseProvider . prototype . registerAppDatabaseURI = registerAppDatabaseURI ;
67
+ DatabaseProvider . prototype . getDatabaseConnections = getDatabaseConnections ;
68
+ DatabaseProvider . prototype . getDatabaseConnection = getDatabaseConnection ;
69
+ DatabaseProvider . prototype . resolveAdapter = resolveAdapter ;
70
+ DatabaseProvider . prototype . DatabaseProvider = DatabaseProvider ;
71
+
72
+ exports = module . exports = new DatabaseProvider ( ) ;
0 commit comments