Git Product home page Git Product logo

unleash-client-node's Introduction

Unleash Client SDK for Node.js

Unleash node SDK on npm npm downloads Build Status Code Climate Coverage Status

The official Unleash client SDK for Node.js.

Getting started

1. Install the unleash-client into your project

npm install unleash-client

or

yarn add unleash-client

(Or any other tool you like.)

2. Initialize unleash-client

Once installed, you must initialize the SDK in your application. By default, Unleash initialization is asynchronous, but if you need it to be synchronous, you can block until the SDK has synchronized with the server.

Note that until the SDK has synchronized with the API, all features will evaluate to false unless you a bootstrapped configuration.


πŸ’‘ Tip: All code samples in this section will initialize the SDK and try to connect to the Unleash instance you point it to. You will need an Unleash instance and a server-side API token for the connection to be successful.


We recommend that you initialize the Unleash client SDK as early as possible in your application. The SDK will set up an in-memory repository and poll for updates from the Unleash server at regular intervals.

import { initialize } from 'unleash-client';

const unleash = initialize({
  url: 'https://YOUR-API-URL',
  appName: 'my-node-name',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
});

The initialize function will configure a global Unleash instance. If you call this method multiple times, the global instance will be changed. You will not create multiple instances.

How do I know when it's ready?

Because the SDK takes care of talking to the server in the background, it can be difficult to know exactly when it has connected and is ready to evaluate toggles. If you want to run some code when the SDK becomes ready, you can listen for the 'synchronized' event:

unleash.on('synchronized', () => {
  // the SDK has synchronized with the server
  // and is ready to serve
});

Refer to the events reference later in this document for more information on events and an exhaustive list of all the events the SDK can emit.

The initialize function will configure and create a global Unleash instance. When a global instance exists, calling this method has no effect. Call the destroy function to remove the globally configured instance.

Constructing the Unleash client directly

You can also construct the Unleash instance yourself instead of via the initialize method.

When using the Unleash client directly, you should not create new Unleash instances on every request. Most applications are expected to only have a single Unleash instance (singleton). Each Unleash instance will maintain a connection to the Unleash API, which may result in flooding the Unleash API.

import { Unleash } from 'unleash-client';

const unleash = new Unleash({
  url: 'https://YOUR-API-URL',
  appName: 'my-node-name',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
});

unleash.on('ready', console.log.bind(console, 'ready'));

// optional error handling when using unleash directly
unleash.on('error', console.error);

Synchronous initialization

You can also use the startUnleash function and await to wait for the SDK to have fully synchronized with the Unleash API. This guarantees that the SDK is not operating on local and potentially stale feature toggle configuration.

import { startUnleash } from 'unleash-client';

const unleash = await startUnleash({
  url: 'https://YOUR-API-URL',
  appName: 'my-node-name',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
});

// Unleash SDK has now fresh state from the unleash-api
const isEnabled = unleash.isEnabled('Demo');

3. Check features

With the SDK initialized, you can use it to check the states of your feature toggles in your application.

The primary way to check feature toggle status is to use the isEnabled method on the SDK. It takes the name of the feature and returns true or false based on whether the feature is enabled or not.

setInterval(() => {
  if (unleash.isEnabled('DemoToggle')) {
    console.log('Toggle enabled');
  } else {
    console.log('Toggle disabled');
  }
}, 1000);

πŸ‘€ Note: In this example, we've wrapped the isEnabled call inside a setInterval function. In the event that all your app does is to start the SDK and check a feature status, this is will keep a node app running until the SDK has synchronized with the Unleash API. It is not required in normal apps.

Providing an Unleash context

Calling the isEnabled method with just a feature name will work in simple use cases, but in many cases you'll also want to provide an Unleash context. The SDK uses the Unleash context to evaluate any activation strategy with strategy constraints, and also to evaluate some of the built-in strategies.

The isEnabled accepts an Unleash context object as a second argument:

const unleashContext = {
  userId: '123',
  sessionId: 'some-session-id',
  remoteAddress: '127.0.0.1',
  properties: {
    region: 'EMEA',
  },
};

const enabled = unleash.isEnabled('someToggle', unleashContext);

4. Stop unleash

To shut down the client (turn off the polling) you can simply call the destroy-method. This is typically not required.

import { destroy } from 'unleash-client';
destroy();

Built in activation strategies

The client comes supports all built-in activation strategies provided by Unleash.

Read more about activation strategies in the official docs.

Unleash context

In order to use some of the common activation strategies you must provide an Unleash context. This client SDK allows you to send in the unleash context as part of the isEnabled call:

const unleashContext = {
  userId: '123',
  sessionId: 'some-session-id',
  remoteAddress: '127.0.0.1',
};
unleash.isEnabled('someToggle', unleashContext);

Advanced usage

The initialize method takes the following arguments:

  • url - The url to fetch toggles from (required).
  • appName - The application name / codebase name (required).
  • environment - The value to put in the Unleash context's environment property. Automatically populated in the Unleash Context (optional). This does not set the SDK's Unleash environment.
  • instanceId - A unique identifier, should/could be somewhat unique.
  • refreshInterval - The poll interval to check for updates. Defaults to 15000ms.
  • metricsInterval - How often the client should send metrics to Unleash API. Defaults to 60000ms.
  • strategies - Custom activation strategies to be used.
  • disableMetrics - Disable metrics.
  • customHeaders - Provide a map(object) of custom headers to be sent to the unleash-server.
  • customHeadersFunction - Provide a function that return a Promise resolving as custom headers to be sent to unleash-server. When options are set, this will take precedence over customHeaders option.
  • timeout - Specify a timeout in milliseconds for outgoing HTTP requests. Defaults to 10000ms.
  • repository - Provide a custom repository implementation to manage the underlying data.
  • httpOptions - Provide custom http options such as rejectUnauthorized - be careful with these options as they may compromise your application security.
  • namePrefix - Only fetch feature toggles with the provided name prefix.
  • tags - Only fetch feature toggles tagged with the list of tags. E.g.: [{type: 'simple', value: 'proxy'}].

Custom strategies

1. implement the custom strategy:

import { initialize, Strategy } from 'unleash-client';
class ActiveForUserWithEmailStrategy extends Strategy {
  constructor() {
    super('ActiveForUserWithEmail');
  }

  isEnabled(parameters, context) {
    return parameters.emails.indexOf(context.email) !== -1;
  }
}

2. register your custom strategy:

initialize({
  url: 'http://unleash.herokuapp.com',
  customHeaders: {
    Authorization: 'API token',
  },
  strategies: [new ActiveForUserWithEmailStrategy()],
});

Events

The unleash instance object implements the EventEmitter class and emits the following events:

event payload description
ready - is emitted once the fs-cache is ready. if no cache file exists it will still be emitted. The client is ready to use, but might not have synchronized with the Unleash API yet. This means the SDK still can operate on stale configurations.
synchronized - is emitted when the SDK has successfully synchronized with the Unleash API, or when it has been bootstrapped, and has all the latest feature toggle configuration available.
registered - is emitted after the app has been registered at the api server
sent object data key/value pair of delivered metrics
count string name, boolean enabled is emitted when a feature is evaluated
warn string msg is emitted on a warning
error Error err is emitted on a error
unchanged - is emitted each time the client gets new toggle state from server, but nothing has changed
changed object data is emitted each time the client gets new toggle state from server and changes has been made
impression object data is emitted for every user impression (isEnabled / getVariant)

Example usage:

import { initialize } from 'unleash-client';

const unleash = initialize({
  appName: 'my-app-name',
  url: 'http://unleash.herokuapp.com/api/',
  customHeaders: {
    Authorization: 'API token',
  },
});

// Some useful life-cycle events
unleash.on('ready', console.log);
unleash.on('synchronized', console.log);
unleash.on('error', console.error);
unleash.on('warn', console.warn);

unleash.once('registered', () => {
  // Do something after the client has registered with the server api.
  // NB! It might not have received updated feature toggles yet.
});

unleash.once('changed', () => {
  console.log(`Demo is enabled: ${unleash.isEnabled('Demo')}`);
});

unleash.on('count', (name, enabled) => console.log(`isEnabled(${name})`));

Bootstrap

(Available from v3.11.x)

The Node.js SDK supports a bootstrap parameter, allowing you to load the initial feature toggle configuration from somewhere else than the Unleash API. The bootstrap data can be provided as an argument directly to the SDK, as a filePath to load or as a url to fetch the content from. Bootstrap is a convenient way to increase resilience, where the SDK can still load fresh toggle configuration from the bootstrap location, even if the Unleash API should be unavailable at startup.

1. Bootstrap with data passed as an argument

const client = initialize({
  appName: 'my-application',
  url: 'https://app.unleash-hosted2.com/demo/api/',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
  bootstrap: {
    data: [
      {
        enabled: false,
        name: 'BootstrapDemo',
        description: '',
        project: 'default',
        stale: false,
        type: 'release',
        variants: [],
        strategies: [{ name: 'default' }],
      },
    ],
  },
});

2. Bootstrap via a URL

const client = initialize({
  appName: 'my-application',
  url: 'https://app.unleash-hosted.com/demo/api/',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
  bootstrap: {
    url: 'http://localhost:3000/proxy/client/features',
    urlHeaders: {
      Authorization: 'bootstrap',
    },
  },
});

3. Bootstrap from a File

const client = initialize({
  appName: 'my-application',
  url: 'https://app.unleash-hosted.com/demo/api/',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
  bootstrap: {
    filePath: '/tmp/some-bootstrap.json',
  },
});

Toggle definitions

Sometimes you might be interested in the raw feature toggle definitions.

import {
  initialize,
  getFeatureToggleDefinition,
  getFeatureToggleDefinitions,
} from "unleash-client";

initialize({
  url: 'http://unleash.herokuapp.com/api/',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
  appName: 'my-app-name',
  instanceId: 'my-unique-instance-id',
});

const featureToggleX = getFeatureToggleDefinition('app.ToggleX');
const featureToggles = getFeatureToggleDefinitions();

Custom Store Provider

(Available from v3.11.x)

By default this SDK will use a store provider that writes a backup of the feature toggle configuration to a file on disk. This happens every time it receives updated configuration from the Unleash API. You can swap out the store provider with either the provided in-memory store provider or a custom store provider implemented by you.

1. Use InMemStorageProvider

import { initialize, InMemStorageProvider } from "unleash-client";

const client = initialize({
  appName: 'my-application',
  url: 'http://localhost:3000/api/',
  customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
  storageProvider: new InMemStorageProvider(),
});

2. Custom Store Provider backed by redis

import { initialize, InMemStorageProvider } from "unleash-client";

import { createClient } from 'redis';

class CustomRedisStore {
  async set(key, data) {
    const client = createClient();
    await client.connect();
    await client.set(key, JSON.stringify(data));
  }
  async get(key) {
    const client = createClient();
    await client.connect();
    const data = await client.get(key);
    return JSON.parse(data);
  }
}

const client = initialize({
  appName: 'my-application',
  url: 'http://localhost:3000/api/',
  customHeaders: {
    Authorization: 'my-key',
  },
  storageProvider: new CustomRedisStore(),
});

Custom repository

You can manage the underlying data layer yourself if you want to. This enables you to use unleash offline, from a browser environment or implement your own caching layer. See example.

Unleash depends on a ready event of the repository you pass in. Be sure that you emit the event after you've initialized unleash.

Design philosophy

This feature flag SDK is designed according to our design philosophy. You can read more about that here.

unleash-client-node's People

Contributors

agardnerit avatar alvinometric avatar andreas-unleash avatar chriswk avatar dependabot[bot] avatar elhoyos avatar fredrikoseberg avatar gastonfournier avatar gnab avatar greenkeeper[bot] avatar henrikbacher avatar ivarconr avatar kwasniew avatar mathjoh avatar meemaw avatar mfolkeseth avatar moolen avatar nunogois avatar phillipj avatar renovate[bot] avatar sbelzile-nexapp avatar sighphyre avatar simenb avatar simenbrekken avatar slauta avatar sveisvei avatar theneva avatar thomasheartman avatar tymek avatar vsandvold avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unleash-client-node's Issues

Client side only execution

Are there any plans to support purely client side execution? I'm running into issues using this library clientside due to calls to fs

An in-range update of lint-staged is breaking the build 🚨

The devDependency lint-staged was updated from 8.1.6 to 8.1.7.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

lint-staged is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v8.1.7

8.1.7 (2019-05-15)

Bug Fixes

  • Resolve security vulnerability in dependencies (#615) (315890a), closes #600
Commits

The new version differs by 2 commits.

  • 315890a fix: Resolve security vulnerability in dependencies (#615)
  • cbf0e0e docs: Correct section about filtering files (#612)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 12.0.0 to 12.0.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Lambda use-case

We use this SDK in a AWS ApiGateway/Lambda context.

AWS recommends that all callbacks/background processes should complete before the function returns [1].

So we should implement it like in this example:

exports.handler = (event, _, callback) => {
    const { initialize, isEnabled } = require('unleash-client');
    const instance = initialize({
        url: process.env.TOGGLE_ENDPOINT,
        appName: 'my-app',
        instanceId: 'my-lambda',
        refreshInterval: 15,
    });
 
    instance.on('ready', () => {
        const enabled = isEnabled(event.toggle, event.context)
        // do something with $enabled
        console.log(`flag ${event.toggle} enabled: ${enabled}`)
        
        // destroy
        instance.destroy();
        callback(null);
    });
}

This means, that each invocation has to call initialize() in a lambda handler and also call instance.destroy() when it completes to properly clean up callbacks and resources. This inevitably issues unnecessary requests to the api server [2] since the user has no access to the internal storage implementation and the user has to wait until unleash as a whole is ready.

We could call initialize() outside the lambda handler - but we then might lose metrics from that instance which is not really what we want. For now, it's a OKish trade-off for us.

Example implementation:

const { initialize, isEnabled } = require('unleash-client');
const instance = initialize({
    url: process.env.TOGGLE_ENDPOINT,
    appName: 'my-app',
    instanceId: 'my-lambda',
    refreshInterval: 1,
});

instance.on('error', (err) => {
    console.log("error ", err)
});

exports.handler = (event, _, callback) => {
    const enabled = isEnabled(event.toggle, event.context)
    console.log(`flag ${event.toggle} enabled: ${enabled}`)
    callback(null);
}

This has the following drawbacks:

  1. during the first invocation there are no feature toggles yet
  2. once AWS wants the lambda to die the metrics from the last $metricsInterval interval are not sent

What we want is to have control over the caching layer and/or the toggle update cycle in order to address this issue.

We'll discuss this internally first and i'll come back with a proposal. For now i think it's valueable to have this "limitation" documented here.

Please tell me if that works for you or when you have input on that topic.

[1] https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html
[2] https://github.com/Unleash/unleash-client-node/blob/master/src/repository.ts#L51

An in-range update of prettier is breaking the build 🚨

The devDependency prettier was updated from 1.14.2 to 1.14.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

prettier is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for 1.14.3

πŸ”— Changelog

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Fix unstable unit-tests

Because tests run to fast we end up writing to backup-repo after test finishes. This causes next test to fail.

We should find a way to avoid all unit-tests using the same backup-files.

An in-range update of husky is breaking the build 🚨

The devDependency husky was updated from 2.2.0 to 2.3.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

husky is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 13 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

pkginfo causes node server to crash when using webpack to bundle dependencies

This issue stems from the unleash client use of the pkginfo module and consumers using a module bundler to inline their server dependencies.

require('pkginfo')(module, 'version');

pkginfo attempts to locate the directory of the package.json as a convenience but doesn't play nice w/ webpack or other module bundlers and ultimately causes NodeJS to throw an error.

This fix here is pretty straight-forward. It's simply a matter of dropping pkginfo as a dependency and using relative paths to import the package.json. Cheers!

Custom Http Header

Hi,
if there is any example how we can use 'customHttpHeader' with node client ?

Improve error handling in RemoteAddressStrategy

If the user has specified an unvalid ip adress the strategy will throw and forcing unleash to throw.

Example of exception when user adds IP="l127.0.0.1":

Error: invalid CIDR subnet: l127.0.0.1
    at Object.ip.cidrSubnet (/home/node/src/node_modules/ip/lib/ip.js:224:11)
    at RemoteAddressStrategy.isEnabled (/home/node/src/node_modules/unleash-client/lib/strategy/remote-addresss-strategy.js:30:24)
    at /home/node/src/node_modules/unleash-client/lib/client.js:77:33
    at Array.some (<anonymous>)
    at UnleashClient.isEnabled (/home/node/src/node_modules/unleash-client/lib/client.js:71:32)
    at Unleash.isEnabled (/home/node/src/node_modules/unleash-client/lib/unleash.js:115:34)

An in-range update of @types/node is breaking the build 🚨

The devDependency @types/node was updated from 10.11.4 to 10.11.5.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Question: Can this be used in a browser?

Hello everyone. I'm trying to use unleash to control my frontend application. I do understand that this client was originally written to be used for a node server application, and currently if I try to use it in a browser, it throws an error. (fs module is not found). Looks like the node client uses fs to store features it fetched from the unleash backend server. I'm wondering if there's a way to switch out the storage in the client so it uses the browser local storage. Thanks in advance!

Test the backupFile feature

The repository uses a backup-file to bootstrap unleash (make the client independent from unleash-server at startup. We should have great test-coverage for this feature.

Fix warnings

  • Currently client/metrics returns 202 - and this logs a warning
  • Missing strategy logs a warn for each isEnabled call. This might generate alot of log-entries...

Add sdkVersion in client-register call

As specified in Unleash/unleash:docs/api/client/register-api.md@master clients should now include sdk type and version identifier.

The value of the of this field should be picked up from package.json and look like:
sdkVersion: unleash-client-node:3.x.z

Missing dependency ip

Strategy remoteAddress depends on ip, but is not present in package.json.

Solution:
npm install ip --save-dev

Why do strategies need to be defined in the client?

Hi,

I am a bit confused why the client needs to define the strategy that will be used to distribute flags (i.e. using the strategies property and custom new Strategy() instances).

I have a custom strategy set up in the Unleash UI, one that has a list parameter (tenantCode), so that, if I have a number of tenantCodes defined, I want to set a flag to true if the client's context includes one of those tenantCodes.

Or in pseudo code:
if client.tenantCode is included in flag.params.tenantCodes, then true.

Now, the client doesn't care about the implementation of this flag, it just wants to send up its context and receive a true or false value.
And yet, I get a "missing strategy" error from unleash-client, if I don't define the exact logic of isEnabled() for this custom strategy inside my consumer code.

Also, if multiple clients are consumers of that flag (with that tenant strategy), now all of them need to have that custom logic implemented and defined as a custom strategy.

This is very weird to me. Imagine I have 6 microservices and 3 different web and mobile apps, all using my tenant Strategy above (for various flags). Some written in Javascript/Node, some in Go, some in Java, some Python.
I am now forced to re-implement the custom Strategy and isEnabled() function in all of them, making sure the different languages don't treat the flag differently because of course they're supposed to be treated identically (by the nature of a server-controlled flag).

Can someone clarify why it is designed this way?
Other systems don't require this (e.g. LaunchDarkly): You define the flag logic on the server and the clients are only responsible for sending up user context and receive back the true/false state of a given flag the client is interested in.

An in-range update of @types/nock is breaking the build 🚨

The devDependency @types/nock was updated from 10.0.2 to 10.0.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/nock is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Dependency problem using with webpack

Hi,

I tried to use the unleash client in a React application and seems that one of the dependencies have some problem with webpack.

Critical dependencies: 1:476-483 This seems to be a pre-built javascript file. Though this is possible, it's not recommended. Try to require the original source to get better results. @ ./~/ajv/dist/ajv.bundle.js 1:476-483

Seems that the request module is not updated and one of the sub dependencies is causing this.

Static configuration

Have you considered having the client to use a static configuration file instead of a server?

Use case

Your project is not a big one, you don't need metrics and just have small set of features to toggle, so you should not need a server and sorts to make this work.

Proposal

const features = {
    'my-feature': {
        name: 'my-feature',
        enabled: true,
        strategies: [{
            name: 'technology',
            parameters: {
                device_category: 'mobile'
            }
        }],
        variants: [
            [{
                name: 'control'
            }, {
                name: 'my-way'
            }]
        ]
    }
};
const { initialize } = require('unleash-client');
const unleash = initialize({ features });

Where features could be a properly formed object or a json filepath string.

Feature reference in variant

As stated in Unleash/unleash#297 (comment) I'm trying to integrate Google Optimize with unleash and at some point I have a special version of feature set that serves well for this purpose:

{
  version: '2.special', // v2 from unleash + optimize experiment id
  features: [{
    name: 'laugh',
    enabled: true,
    description: 'Experiment a new world surrounded by laugh',
    goExperimentId: 'HXEMMfooUiQQ6zMKDI4guivw',
    strategies: [...],
    variants: [...],
  }, ...
}

And later in the pipeline I need access to the goExperimentId value in order to signal Google Optimize about the experiment to be using.

Right now, I'm sorts of doing the following:

const feature = conf.unleashFeatures.features.find(f => f.name === featureName);
ga.signalExperiment(feature.goExperimentId, variant.id);

However I find the lookup step kind of unnecessary. Do you see any negative consequence on referencing the Feature from within a Variant?

ga.signalExperiment(variant.feature.goExperimentId, variant.id);

feat: add support static context fields

In order to prepare the SDKS for strategy constraints we need to introduce two new fields in the Unleash Context

  • environment (default value is "default")
  • appName (already a required config parameter)

Both these static context fields should be configured at initialisation of the unleash SDK and be set as default values of the Unleash Context provided to the strategy implementations. The user is allowed to override these values in the context object at runtime (this is required to be backward compatible).

This support should be possible to add without breaking any contract and should be released as a minor version (3.3.x).

Unhandled error when initializing client for unknown user

This was discovered while running autotests for our app so is probably not critical to production.

If the Unleash client is initialized without specifying an instanceId then the client will attempt to generate one using os.userInfo and os.hostname. This can result in an unhandled error in some cases because os.userInfo will throw an error if the user running the process does not have an entry in the /etc/passwd file on *nix systems. Here is a stack trace from our app:

/usr/src/app/node_modules/unleash-client/lib/unleash.js:44
            var info = os_2.userInfo();
                            ^

Error: ENOENT: no such file or directory, uv_os_get_passwd
    at Error (native)
    at new Unleash (/usr/src/app/node_modules/unleash-client/lib/unleash.js:44:29)
    at initialize (/usr/src/app/node_modules/unleash-client/lib/index.js:8:16)

See GetUserInfo in Node's os module:

https://github.com/nodejs/node/blob/master/src/node_os.cc#L354

Since there is already a fallback for the case where info.username is empty, it probably makes sense to put a try/catch around the call to userInfo() and ensure the fallback gets used if an error is thrown.

In the meantime, the workaround is simply to pass in a instanceId when initializing Unleash.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.