File tree 2 files changed +44
-6
lines changed
2 files changed +44
-6
lines changed Original file line number Diff line number Diff line change @@ -31,6 +31,12 @@ var Service = require('@google-cloud/common').Service;
31
31
var through = require ( 'through2' ) ;
32
32
var util = require ( '@google-cloud/common' ) . util ;
33
33
34
+ /**
35
+ * @const {object} - A cache of proto objects.
36
+ * @private
37
+ */
38
+ var protoObjectCache = { } ;
39
+
34
40
/**
35
41
* @const {object} - A map of protobuf codes to HTTP status codes.
36
42
* @private
@@ -752,13 +758,22 @@ GrpcService.prototype.loadProtoFile_ = function(protoConfig, config) {
752
758
} ;
753
759
}
754
760
755
- var services = grpc . load ( {
756
- root : config . protosDir ,
757
- file : protoConfig . path
758
- } , 'proto' , grpcOpts ) ;
761
+ var protoObjectCacheKey = [
762
+ config . protosDir ,
763
+ protoConfig . path ,
764
+ protoConfig . service
765
+ ] . join ( '$' ) ;
766
+
767
+ if ( ! protoObjectCache [ protoObjectCacheKey ] ) {
768
+ var services = grpc . load ( {
769
+ root : config . protosDir ,
770
+ file : protoConfig . path
771
+ } , 'proto' , grpcOpts ) ;
772
+ var service = dotProp . get ( services . google , protoConfig . service ) ;
773
+ protoObjectCache [ protoObjectCacheKey ] = service ;
774
+ }
759
775
760
- var service = dotProp . get ( services . google , protoConfig . service ) ;
761
- return service ;
776
+ return protoObjectCache [ protoObjectCacheKey ] ;
762
777
} ;
763
778
764
779
/**
Original file line number Diff line number Diff line change @@ -1780,6 +1780,29 @@ describe('GrpcService', function() {
1780
1780
assert . strictEqual ( service , fakeServices . google . FakeService ) ;
1781
1781
} ) ;
1782
1782
1783
+ it ( 'should cache the expensive proto object creation' , function ( ) {
1784
+ var protoConfig = {
1785
+ path : '/root/dir/path' ,
1786
+ service : 'FakeService'
1787
+ } ;
1788
+
1789
+ var mainConfig = {
1790
+ service : 'OtherFakeService' ,
1791
+ apiVersion : 'v2'
1792
+ } ;
1793
+
1794
+ var gprcLoadCalled = 0 ;
1795
+ grpcLoadOverride = function ( ) {
1796
+ gprcLoadCalled ++ ;
1797
+ return fakeServices ;
1798
+ } ;
1799
+
1800
+ var service1 = grpcService . loadProtoFile_ ( protoConfig , mainConfig ) ;
1801
+ var service2 = grpcService . loadProtoFile_ ( protoConfig , mainConfig ) ;
1802
+ assert . strictEqual ( service1 , service2 ) ;
1803
+ assert . strictEqual ( gprcLoadCalled , 1 ) ;
1804
+ } ) ;
1805
+
1783
1806
it ( 'should return the services object if invalid version' , function ( ) {
1784
1807
var fakeProtoConfig = {
1785
1808
path : '/root/dir/path' ,
You can’t perform that action at this time.
0 commit comments