Skip to content

Latest commit

 

History

History
273 lines (189 loc) · 7.85 KB

File metadata and controls

273 lines (189 loc) · 7.85 KB

apollo-node-client

Node.js Client for Apollo

English | 简体中文

v2.0+ supports both CommonJS and ESM. 1.x only supports CommonJS.

Install

$ npm install apollo-node-client --save

Examples

examples

Usage

Create a ConfigService

CommonJS:

const { ConfigService } = require('apollo-node-client');

ESM:

import { ConfigService } from 'apollo-node-client';

Then create an instance:

const service = new ConfigService({
  configServerUrl: 'http://localhost:8080/',
  appId: 'SampleApp',
  clusterName: 'default',
  secret: 'cf86d564d10a46d4a5989dfdeed3a3a2'
});

Get the default namespace config (application)

const config = await service.getAppConfig();
config.getAllConfig();                                          // Map(1) { 'mysql.user' => 'root' }
console.log(config.getProperty('mysql.user'));                  // root
console.log(config.getProperty('mysql.missing', 'default'));    // default

Get properties format namespace config

const config = await service.getConfig('application');
config.getAllConfig();                                          // Map(1) { 'mysql.user' => 'root' }
console.log(config.getProperty('mysql.user'));                  // root
console.log(config.getProperty('mysql.missing', 'default'));    // default

Get json format namespace config

const config = await service.getConfig('config.json');
config.getAllConfig();                                          // { mysql: { user: 'root' } }
console.log(config.getProperty('mysql.user'));                  // root
console.log(config.getProperty('mysql.missing', 'default'));    // default

Get xml/yml/yaml/txt format namespace config

const config = await service.getConfig('config.txt');
config.getAllConfig();                                          // txt config
console.log(config.getProperty('', 'default'));                 // txt config
console.log(config.getProperty());                              // txt config

Specify canary release ip or label

const config = await service.getConfig('application', '192.168.3.4');
config.getAllConfig();                                          // Map(1) { 'mysql.user' => 'root' }
console.log(config.getProperty('mysql.user'));                  // root
console.log(config.getProperty('mysql.missing', 'default'));    // default

The string second argument is kept as the server ip for backwards compatibility. Use an options object when you need label or both ip and label:

const labelConfig = await service.getConfig('application', {
  label: 'gray',
});

const ipAndLabelConfig = await service.getConfig('application', {
  ip: '192.168.3.4',
  label: 'gray',
});

Configs are cached by namespace, ip, and label. Calling getConfig('application', '192.168.3.4') and getConfig('application', '192.168.3.5') returns different config instances.

Listen for config change events

config.addChangeListener((changeEvent) => {
  for (const key of changeEvent.changedKeys()) {
    const change = changeEvent.getChange(key);
    if (change) {
      console.log(`namespace: ${change.getNamespace()},
        changeType: ${change.getChangeType()},
        propertyName: ${change.getPropertyName()},
        oldValue: ${change.getOldValue()},
        newValue: ${change.getNewValue()}`);
    }
  }
});

Stop long polling

service.close();

close() stops background long polling and clears cached config instances held by the service. Existing config objects can still read their last loaded values, but they will no longer update.

API

Class: ConfigService

  • new ConfigService( options )

    • options <Object>

      • configServerUrl <string> Apollo config server URL
      • appId <string> Application ID
      • [clusterName] <string> Cluster name
      • [secret] <string> Access key secret
    • Returns: ConfigService

  • configService.getAppConfig( [ ipOrOptions ] )

    • [ipOrOptions] <string | Object> Server IP string or request options for canary release

      • [ip] <string> Server IP for canary release
      • [label] <string> Apollo label for grayscale release
    • Returns: Promise<PropertiesConfig> Default namespace is application

  • configService.getConfig( namespaceName, [ ipOrOptions ] )

    • namespaceName <string> Namespace name. The config format is determined by the file extension. Defaults to properties if no extension. Supports .json, .properties, .xml, .yml, .yaml, .txt

    • [ipOrOptions] <string | Object> Server IP string or request options for canary release

      • [ip] <string> Server IP for canary release
      • [label] <string> Apollo label for grayscale release
    • Returns: Promise<PropertiesConfig | JSONConfig | PlainConfig>

  • configService.close()

    • Stops long polling and clears cached config instances.

    • Returns: void

Initial load errors are logged and the config instance is still returned. The service keeps long polling, so later successful Apollo responses can still populate or update the config.


Class: PropertiesConfig

  • propertiesConfig.getAllConfig()

    • Returns: Map<string, string> A copy of the current configs.
  • propertiesConfig.getProperty( key, [ defaultValue ] )

    • key <string> Config key to retrieve

    • [defaultValue] <string> Default value returned when the key does not exist

    • Returns: undefined | string

  • propertiesConfig.addChangeListener( handle )

    • handle ( changeEvent: ConfigChangeEvent<string> ) => void Callback for config change events

    • Returns: PropertiesConfig


Class: JSONConfig

  • jsonConfig.getAllConfig()

    • Returns: JSONValueType A copy of the current configs.
  • jsonConfig.getProperty( key, [ defaultValue ] )

    • key <string> Config key to retrieve

    • [defaultValue] <JSONValueType> Default value returned when the key does not exist

    • Returns: undefined | JSONValueType

    • Dot-separated keys are used for object traversal, for example mysql.user. Array indexes are not traversed. Invalid JSON namespace content is returned as a plain string for backward compatibility.

  • jsonConfig.addChangeListener( handle )

    • handle ( changeEvent: ConfigChangeEvent<JSONValueType> ) => void Callback for config change events

    • Returns: JSONConfig


Class: PlainConfig

  • plainConfig.getAllConfig()

    • Returns: string
  • plainConfig.getProperty( key, [ defaultValue ] )

    • [key] <string> Compatible with other config types. Any key returns the entire config text

    • [defaultValue] <string> Default value returned when the config does not exist

    • Returns: undefined | string

  • plainConfig.addChangeListener( handle )

    • handle ( changeEvent: ConfigChangeEvent<string> ) => void Callback for config change events

    • Returns: PlainConfig


Class: ConfigChangeEvent

  • configChangeEvent.getNamespace()

    • Returns: string
  • configChangeEvent.changedKeys()

    • Returns: string[]
  • configChangeEvent.getChange()

    • Returns: undefined | ConfigChange<T>

Class: ConfigChange<T>

  • configChange.getNamespace()

    • Returns: string
  • configChange.getPropertyName()

    • Returns: string
  • configChange.getOldValue()

    • Returns: undefined | T
  • configChange.getNewValue()

    • Returns: undefined | T
  • configChange.getChangeType()

    • Returns: PropertyChangeType

Enum: PropertyChangeType

  • propertyChangeType.ADDED

  • propertyChangeType.MODIFIED

  • propertyChangeType.DELETED


Contributing

Contributions are always welcome!

License

MIT