19
19
import { spawn } from 'child-process-promise' ;
20
20
import { ChildProcess } from 'child_process' ;
21
21
import * as fs from 'fs' ;
22
+ import * as os from 'os' ;
22
23
import * as path from 'path' ;
23
24
import * as request from 'request' ;
24
25
// @ts -ignore
@@ -28,13 +29,25 @@ export abstract class Emulator {
28
29
binaryPath : string | null = null ;
29
30
emulator : ChildProcess | null = null ;
30
31
32
+ cacheDirectory : string ;
33
+ cacheBinaryPath : string ;
34
+
31
35
constructor (
32
36
private binaryName : string ,
33
37
private binaryUrl : string ,
34
38
public port : number
35
- ) { }
39
+ ) {
40
+ this . cacheDirectory = path . join ( os . homedir ( ) , `.cache/firebase-js-sdk` ) ;
41
+ this . cacheBinaryPath = path . join ( this . cacheDirectory , binaryName ) ;
42
+ }
36
43
37
44
download ( ) : Promise < void > {
45
+ if ( fs . existsSync ( this . cacheBinaryPath ) ) {
46
+ console . log ( `Emulator found in cache: ${ this . cacheBinaryPath } ` ) ;
47
+ this . binaryPath = this . cacheBinaryPath ;
48
+ return Promise . resolve ( ) ;
49
+ }
50
+
38
51
return new Promise < void > ( ( resolve , reject ) => {
39
52
tmp . dir ( ( err : Error | null , dir : string ) => {
40
53
if ( err ) reject ( err ) ;
@@ -55,6 +68,10 @@ export abstract class Emulator {
55
68
if ( err ) reject ( err ) ;
56
69
console . log ( `Changed emulator file permissions to 'rwxr-xr-x'.` ) ;
57
70
this . binaryPath = filepath ;
71
+
72
+ if ( this . copyToCache ( ) ) {
73
+ console . log ( `Cached emulator at ${ this . cacheBinaryPath } ` ) ;
74
+ }
58
75
resolve ( ) ;
59
76
} ) ;
60
77
} )
@@ -129,4 +146,23 @@ export abstract class Emulator {
129
146
fs . unlinkSync ( this . binaryPath ) ;
130
147
}
131
148
}
149
+
150
+ private copyToCache ( ) : boolean {
151
+ if ( ! this . binaryPath ) {
152
+ return false ;
153
+ }
154
+
155
+ try {
156
+ if ( ! fs . existsSync ( this . cacheDirectory ) ) {
157
+ fs . mkdirSync ( this . cacheDirectory , { recursive : true } ) ;
158
+ }
159
+ fs . copyFileSync ( this . binaryPath , this . cacheBinaryPath ) ;
160
+
161
+ return true ;
162
+ } catch ( e ) {
163
+ console . warn ( `Unable to cache ${ this . binaryName } ` , e ) ;
164
+ }
165
+
166
+ return false ;
167
+ }
132
168
}
0 commit comments