featurehub-javascript-sdk

所属分类:数学计算
开发工具:TypeScript
文件大小:0KB
下载次数:0
上传日期:2023-11-18 21:17:14
上 传 者sh-1993
说明:  官方功能中心Javascript、Typescript、React、SolidJS、Node SDK
(Official FeatureHub Javascript, Typescript, React, SolidJS, Node SDKs)

文件列表:
.dockerignore (43, 2023-11-18)
.husky/ (0, 2023-11-18)
.husky/pre-commit (69, 2023-11-18)
.prettierignore (64, 2023-11-18)
.prettierrc.json (258, 2023-11-18)
Dockerfile (385, 2023-11-18)
LICENSE (1067, 2023-11-18)
examples/ (0, 2023-11-18)
examples/todo-angular/ (0, 2023-11-18)
examples/todo-angular/angular-featurehub-app/ (0, 2023-11-18)
examples/todo-angular/angular-featurehub-app/.browserslistrc (703, 2023-11-18)
examples/todo-angular/angular-featurehub-app/.editorconfig (274, 2023-11-18)
examples/todo-angular/angular-featurehub-app/angular.json (3988, 2023-11-18)
examples/todo-angular/angular-featurehub-app/e2e/ (0, 2023-11-18)
examples/todo-angular/angular-featurehub-app/e2e/protractor.conf.js (904, 2023-11-18)
examples/todo-angular/angular-featurehub-app/e2e/src/ (0, 2023-11-18)
examples/todo-angular/angular-featurehub-app/e2e/src/app.e2e-spec.ts (673, 2023-11-18)
examples/todo-angular/angular-featurehub-app/e2e/src/app.po.ts (274, 2023-11-18)
examples/todo-angular/angular-featurehub-app/e2e/tsconfig.json (274, 2023-11-18)
examples/todo-angular/angular-featurehub-app/karma.conf.js (1439, 2023-11-18)
examples/todo-angular/angular-featurehub-app/package.json (1344, 2023-11-18)
... ...

**Client SDK** [![Build featurehub-javascript-client-sdk](https://github.com/featurehub-io/featurehub-javascript-sdk/actions/workflows/typescript-client-build.yml/badge.svg)](https://github.com/featurehub-io/featurehub-javascript-sdk/actions/workflows/typescript-client-build.yml) [![npm version](https://badge.fury.io/js/featurehub-javascript-client-sdk.svg)](https://badge.fury.io/js/featurehub-javascript-client-sdk) **Node SDK** [![Build featurehub-javascript-node-sdk](https://github.com/featurehub-io/featurehub-javascript-sdk/actions/workflows/typescript-node-build.yml/badge.svg)](https://github.com/featurehub-io/featurehub-javascript-sdk/actions/workflows/typescript-node-build.yml) [![npm version](https://badge.fury.io/js/featurehub-javascript-node-sdk.svg)](https://badge.fury.io/js/featurehub-javascript-node-sdk) | Documentation | Changelog | Example Quick links | |---|---|---| | [FeatureHub platform docs](https://docs.featurehub.io) | [Changelog Client SDK](https://github.com/featurehub-io/featurehub-javascript-sdk/blob/main/featurehub-javascript-client-sdk/CHANGELOG.md)
[Changelog Node SDK](https://github.com/featurehub-io/featurehub-javascript-sdk/blob/main/featurehub-javascript-node-sdk/CHANGELOG.md) | [React example](https://github.com/featurehub-io/featurehub-javascript-sdk/tree/main/examples/todo-frontend-react-typescript)
[Node example](https://github.com/featurehub-io/featurehub-javascript-sdk/tree/main/examples/todo-backend-typescript)
[Angular example](https://github.com/featurehub-io/featurehub-javascript-sdk/tree/main/examples/todo-angular/angular-featurehub-app)
[Test automation example](https://github.com/featurehub-io/featurehub-javascript-sdk/tree/main/examples/todo-server-tests)
[React Catch & Release mode example](https://github.com/featurehub-io/featurehub-javascript-sdk/tree/main/examples/todo-frontend-react-typescript-catch-and-release)
[React Feature Overrides example](https://github.com/featurehub-io/featurehub-javascript-sdk/tree/main/examples/todo-frontend-react-typescript-feature-override) | # Javascript/Typescript SDK for FeatureHub ## Overview Welcome to the Javascript/Typescript SDK implementation for [FeatureHub.io](https://featurehub.io) - Open source Feature flags management, A/B testing and remote configuration platform. This documentation covers both [featurehub-javascript-node-sdk](https://www.npmjs.com/featurehub-javascript-node-sdk) and [featurehub-javascript-client-sdk](https://www.npmjs.com/featurehub-javascript-client-sdk) and explains how you can use the FeatureHub SDK in Javascript or Typescript for applications like Node.js backend servers, Web front-ends (e.g. Vanilla, React, Angular) or Mobile apps (React Native, Ionic, etc.). To control the feature flags from the FeatureHub Admin console, either use FeatureHub SaaS cloud version [demo](https://app.featurehub.io) or install the app using our guide [here](https://docs.featurehub.io/featurehub/latest/installation.html) ## SDK installation Run to install the dependency: if you are intending to use this SDK with React, Angular and other browser frameworks: `npm install featurehub-javascript-client-sdk` if you are using NodeJS use `npm install featurehub-javascript-node-sdk` (and further imports you see below should refer to this node library instead of the client library) ## Options to get feature updates There are 2 ways to request for feature updates via this SDK: - **FeatureHub polling client (GET request updates)** In this mode, you make a GET request, which you can choose to either do once, when specific things happen in your application, (such as navigation change) or on a regular basis (say every 5 minutes) and the changes will be passed into the FeatureHub repository for processing. This mode is recommended for browser type applications (React, Angular, Vue) and Mobile applications. The `featurehub-javascript-client-sdk` defaults to this behaviour as of 1.2.0, and we have updated and streamlined the browser API to reflect this. - **SSE (Server Sent Events) realtime updates mechanism** In this mode, you will make a connection to the FeatureHub Edge server using the EventSource, and any updates to any features will come through to you in _near realtime_, automatically updating the feature values in the repository. This method is recommended for server (Node) applications. `featurehub-javascript-node-sdk` is configured to use SSE by default. If you decide to use SSE in the browser applications, there is a known issues in the browsers with Kaspersky antivirus potentially blocking SSE events. [GitHub issue](https://github.com/featurehub-io/featurehub/issues/296) ## Browser Quick Start ### Connecting to FeatureHub There are 3 steps to connecting: 1) Copy FeatureHub API Key from the FeatureHub Admin Console 2) Create FeatureHub config 3) Request feature state #### 1. API Key from the FeatureHub Admin Console Find and copy your Server Eval API Key from the FeatureHub Admin Console on the API Keys page - you will use this in your code to configure feature updates for your environments. _Server Side evaluation_ is more suitable when you are using an _insecure client_. (e.g. Browser or Mobile). This means your application is reflecting the actions of a single person. It should look similar to this: ```5e61fd62-d4ed-40e0-9cc1-cb3d809f6149/YDr1E4uQGA2Li54fQ0HpmSr2LMv9yHhwzxut2DRO```. There are other variations of applications where you might want to use a key in a different way from above, we cover more on this [in the main FeatureHub documentation](https://docs.featurehub.io/featurehub/latest/sdks.html#_client_and_server_api_keys) #### 2. Create FeatureHub config: In your page's HTML, add the following (replacing the urls and keys with your own server details): ```html ``` The interval indicates polling frequency to get feature updates and set at 15 seconds. It is normal and expected that your API key will be exposed to the end user in this case, as it is intended to be used in insecure environments. ```typescript import { FeatureHub } from 'featurehub-javascript-client-sdk'; ``` The above code configured a server evaluated connection and immediately requests to connect and get the features from the server. See below for why you might want to delay this. #### 3. Request feature state In a standard browser situation, there is a single active connection to the FeatureHub server. You can ask for the feature state in your conditional code (we use a boolean flag here): ```typescript if (FeatureHub.feature('FEATURE_KEY').enabled) { } ``` There is always a possibility of a delay between loading the page and the initial state of the features loading. If your conditional code executes before the features load (e.g. it has never loaded before or the cache we store of features in `localStorage` hasn't loaded yet), you will get an "empty" feature - which will generally evaluate all boolean flags to disabled/false, and all other types of flags to empty. They may not exist, but you can _react_ to changes in feature state. If you wish parts of your page to render when the feature repository gains state, you can listen for the event `addReadynessListener`: ```typescript FeatureHub.config.addReadynessListener((_, firstTimeReady) => { if (firstTimeReady) { // its ready and its the first time it has been ready, so make appropriate screen changes const value = fhConfig.feature('FEATURE_STRING').str; console.log('Value is ', value); } }); ``` Alternatively, you can listen for updates in specific features. ```typescript FeatureHub.feature('FEATURE_KEY').addListener((feature) => { if (feature.flag) { // perform some UI update } }); ``` You can listen to these events at any point, the state of the features doesn't need to be loaded yet. # Quick Start for NodeJS ## Step 1: Getting an apiKey Generally for a nodejs application (unless its a batch application) you would use a _client evaluated key_. _Client Side evaluation_ is intended for use in secure environments (such as microservices, e.g Node JS) and is intended for rapid client side evaluation, per request for example. This also means all of the feature flag targeting information comes down to the server application and it can make complex feature decisions locally. ## Step 2: Setting up your configuration Set the location of your FeatureHub server, your API key and other global information via environment variables: ```typescript const fhConfig = new EdgeFeatureHubConfig(process.env.FEATUREHUB_EDGE_URL, process.env.FEATUREHUB_CLIENT_API_KEY).init(); ``` In this case, we are creating a global connection and adding it to the startup of the application and telling it to kick off. We recommend that for a server application, you include the _readyness_ of the FeatureHub connection in your health check, so don't let the deployment orchestration (be it a FaaS, kubernetes, ECS, etc) let any traffic route to your server unless you have a healthy connection to FeatureHub (just like you could with a database): ```typescript server.get('/health/liveness', (req, res, next) => { if (fhConfig.readyness === Readyness.Ready) { // other checks also here res.status(200); res.send('ok'); } else { res.send('not ready'); res.status(500); } next(); }); ``` ### Adding middleware To personalise the results for each person, FeatureHub uses _Contexts_ - in browser mode there is only one as a browser represents a single user, but in your NodeJS server app, each request can represent a different person. Your middleware is typically where you will create the per-request context and personalise it. ```typescript import { FeatureHubConfig } from './feature_hub_config'; export function userMiddleware(fhConfig: FeatureHubConfig) { return (req: any, res: any, next: any) => { const user = detectUser(req); // function to analyse the Bearer token and determine who the user is let fhClient = fhConfig.newContext(); if (user) { fhClient = fhClient.userKey(user.email); // add anything else relevant to the context } fhClient = fhClient.build().then(() => { req.featureContext = fhClient; next(); }); }; } ``` ## Step 3: Using it in your application In a GET method, determine which message to send: ```typescript app.get('/', function (req, res) { if (req.featureContext.feature('FEATURE_KEY').enabled) { req.send('The feature is enabled'); } else { res.send('The feature is disabled.'); } }) ``` # Beyond the Quick Start: In this section we cover a bundle of different variations for clients and servers. ### Does my existing code from 1.x work? If you have browser code that uses the version earlier than 1.2.0, it still works largely the same and its unlikely you will need to change anything. The biggest change we made in 1.2.+ is in the browser handling. The 99% use case for a browser is a single user, so that means requests for a new context (`FeatureHub.config.newContext()` for example) always actually give you back exactly the same context. And we reference count your requests as well, once your connection is open, its open until all requests to create a new context also close them. If you actually _want_ a second (or third, or forth) context in a browser, you can absolutely get one, you will need to create one - a new `ServerEvalFeatureContext`. ### Can the browser initialize like the NodeJS example? Yes, the `` tag headers are simply an easy way to initialise we introduced in the 1.2.0 version of the API. Single Page Applications (SPA) may not have meta tags and may wish to control exactly how libraries and objects in libraries are made available. As it is still a browser application, you will want to delay your initialization. ```typescript const fhConfig = new EdgeFeatureHubConfig('', ''); // no .init() const fhContext = fhConfig.newContext(); // ... fill in any extra detail in the context await fhContext.build(); // the await is optional ``` If you want to ensure you can use the global `FeatureHub` class, then simply set it with: ```typescript FeatureHub.set(fhConfig); ``` ### What is meant by extra detail? How do I use the strategies attached to feature flags? FeatureHub is able to provide user targeting - to support progressive rollouts, targeted rollouts and even A/B testing. This will require you to pass ClientContext. When you create config and immediately initialize it, it doesn't contain any Client Context information, however you can customise this connection at any time and add the context: Example to specify the languages and username of the person up front you can do this: ```typescript const fhConfig = EdgeFeatureHubConfig.config(edgeUrl, apiKey); fhConfig.newContext().userKey('').attributeValues('languages', navigator.languages).build(); ``` This tells the SDK to hold onto those pieces of information and provide targeted evaluation against them. **Important Note** - you can change these at any time, just remember to add `.build()` on the end. You also do not require the `init()` because the `.build()` will do it for you. ### What is the deal with readyness? Readyness indicates when the SDK has received state or failed to receive state. There is an event on the SDK called `addReadynessListener`. You get two pieces of information, the readyness status and whether its the first time its been ready. This is often the information you need to kick your UI into gear in some way. ```typescript FeatureHub.config.addReadinessListener((readyness, firstTimeReady) => { if (firstTimeReady) { const color = FeatureHub.context.getString('SUBMIT_COLOR_BUTTON'); this.setState({todos: this.state.todos.changeColor(color)}); } }); ``` If you are writing a server application, it would be typical to include the features being available in a health check (as in the Quick Start). If your server is not able to get its features, it should not receive traffic as a general rule. You can always ask the config what the readiness is. ```typescript fhConfig.readiness() ``` ### Changing the polling interval If you are directly creating the EdgeFeatureHubConfig or you are using polling in your app for some other reason, you may wish to change the interval. So you can change it by setting the provider for the "Edge Connector". An example that sets it to five seconds is as follows: ```typescript import { FeatureHubPollingClient } from 'featurehub-javascript-client-sdk'; const FREQUENCY = 5000; // 5 seconds EdgeFeatureHubConfig.edgeServiceProvider((repo, config) => new FeatureHubPollingClient(repo, config, FREQUENCY)); ``` You can specify however many seconds you want. FeatureHub also has the ability for the server to override the polling interval, either globally or per environment, but that is not covered here. Note, NodeJS servers use the SSE real time streaming updater, they can swap to using polling via the same mechanism as above. Please note - you should do this before doing an `EdgeFeatureHubConfig.config()`. ### Changing to SSE (Server Sent Events) - real time streaming updates If you are keen to see real time updates, then swapping to the Streaming connector is achieved by: ```typescript EdgeFeatureHubConfig.defaultEdgeServiceSupplier = (repository, config) => new FeatureHubEventSourceClient(config, repository); ``` This is a default method for feature updates in the featurehub-node-sdk. ## General Documentation #### Supported feature state requests On a context, you can ask for the following information. In the browser, the context is available with `FeatureHub.context`, to make it available in a server app, it is shown in the Quick Start. * Get a raw feature value through the following methods: - `feature('FEATURE_KEY').value` returns whatever the value of this type is as an `any` type. This function is generic so you can use `const colour = feature('FEATURE_COLOUR').value` for instance and it will support Typescript generic typing. This method is also available directly on `FeatureHub`. - `getFlag('FEATURE_KEY') | getBoolean('FEATURE_KEY')` returns a _boolean_ type feature value - _true_ or _false_. Returns _undefined_ if the feature does not exist or not of _boolean_ type. Alternatively use `feature('FEATURE_KEY').flag` - `getNumber('FEATURE_KEY')` returns a _number_ type feature value or _undefined_ if the feature does not exist, or its value not of number type, or feature has no default value. Alternatively use `feature('FEATURE_KEY').num`. - `getString('FEATURE_KEY')` returns a _string_ type feature value or _undefined_ if the feature does not exist, or its value not of string type or feature has no default value. Alternatively use `feature('FEATURE_KEY').str`. - `getRawJson('FEATURE_KEY')` returns a raw json feature value represented as _string_ or _undefined_ if the feature does not exist, or its value not of JSON type or feature has no default value. Alternatively use `feature('FEATURE_KEY').rawJson`. * Use convenience functions: - `isEnabled('FEATURE_KEY')` - returns _true_ only if the feature is a boolean and is _true_, otherwise _false_. Alternatively use `feature('FEATURE_KEY').enabled` - `isSet('FEATURE_KEY')` - in case a feature value is not set (_null_) (this can only happen for strings, numbers and json types), this check returns _false_. If a feature doesn't exist - returns _false_. Otherwise, returns _true_. - `getKey()`: returns feature key if feature exists - `feature('FEATURE_KEY').exists` - return _true_ if feature exists, otherwise return _false_ - `feature('FEATURE_KEY').locked` - returns _true_ if feature is locked, otherwise _false_ - `feature('FEATURE_KEY').version` - returns feature update version number (every change on the feature causes its version to update). - `feature('FEATURE_KEY').type` - returns type of feature (boolean, string, number or json) - `feature('FEATURE_KEY').addListener` - see _Feature updates listener_ below. * Get a list of all feature keys from the feature repository ``` const fhClient = await fhConfig.newContext().build(); console.log("List all feature keys: ", client.repository().simpleFeatures().keys()); ``` * The primitives to build almost any experience you like is available in the SDK, please feel free to have a look around! ## Rollout Strategies and Client Context FeatureHub supports client and server side evaluation of complex rollout strategies that are applied to individual feature values in a specific environment. This includes support of preset rules, e.g. per **_user key_**, **_country_**, **_device type_**, **_platform type_** as well as **_percentage splits_** rules and custom rules that you can create according to your application needs. Client Contexts are _mutable_ objects - which means you can keep changing them as you need to. * For server side evaluation, you need to indicate when you have finished a set of changes and call `.build()`. This grabs all of the attributes in a context evaluation and sends them off to the server for evaluation to ... ...

近期下载者

相关文件


收藏者