@absmartly/javascript-sdk 中文文档教程

发布于 3年前 浏览 30 项目主页 更新于 3年前

A/B Smartly SDK npm version

A/B Smartly - JavaScript SDK

Compatibility

A/B Smartly Javascript SDK 是一个用于 Node.js(CommonJS 和 ES6)和浏览器(UMD)的同构库。

它在 Node.js 版本 6.x 和 npm 3.x 或更高版本上受支持。

它支持 IE 10+ 和所有其他主要浏览器。

注意:IE 10 本身不支持 Promises。 如果你的目标是 IE 10,你必须包含像 es6-promisersvp

Installation

npm

npm install @absmartly/javascript-sdk --save

Import in your Javascript application

const absmartly = require('@absmartly/javascript-sdk');
// OR with ES6 modules:
import absmartly from '@absmartly/javascript-sdk';

Directly in the browser

您可以通过 unpkg.com 在您的 HTML 代码中直接包含优化的预构建包。

只需将以下代码添加到您的 head 部分即可包含最新发布的版本。

    <script src="https://unpkg.com/@absmartly/javascript-sdk/dist/absmartly.min.js"></script>

Getting Started

在尝试以下代码之前,请按照安装 说明进行操作:

Initialization

此示例假定已在 A/B Smartly Web 控制台中创建了一个 Api 密钥、一个应用程序和一个环境。

// somewhere in your application initialization code
const sdk = new absmartly.SDK({
    endpoint: 'https://sandbox.absmartly.io/v1',
    apiKey: process.env.ABSMARTLY_API_KEY,
    environment: process.env.NODE_ENV,
    application: process.env.APPLICATION_NAME,
});

Creating a new Context with raw promises

// define a new context request
const request = {
    units: {
        session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
    },
};

// create context with raw promises
const context = sdk.createContext(request);

context.ready().then((response) => {
    console.log("ABSmartly Context ready!")
}).catch((error) => {
    console.log(error);
});

Creating a new Context with async/await

// define a new context request
const request = {
    units: {
        session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
    },
};

// create context with raw promises
const context = sdk.createContext(request);

try {
    await context.ready();
    console.log("ABSmartly Context ready!")
} catch (error) {
    console.log(error);
}

Creating a new Context with pre-fetched data

在使用 A/B Smartly 进行全栈实验时,我们建议只在服务器端创建一次上下文。 创建上下文涉及到 A/B Smartly 事件收集器的往返。 我们可以通过发送嵌入在第一个文档中的服务器端数据来避免在客户端重复往返,例如,通过在模板上渲染它。 然后我们可以直接用它在客户端初始化A/B Smartly上下文。

    <head>
        <script type="javascript">
            const request = {
                units: {
                    session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
                },
            };

            const context = sdk.createContextWith(request, {{ serverSideContext.data() }});
        </script>
    </head>

Setting context attributes

attribute()attributes() 方法可以在上下文准备好之前调用。

context.attribute('user_agent', navigator.userAgent);

context.attributes({
    customer_age: 'new_customer',
});

Selecting a treatment

if (context.treament("exp_test_experiment") == 0) {
    // user is in control group (variant 0)
} else {
    // user is in treatment group
}

Tracking a goal achievement

目标是在 A/B Smartly 网络控制台中创建的。

context.track("payment", { item_count: 1, total_amount: 1999.99 });

Publishing pending data

有时有必要确保所有事件都已发布到 A/B Smartly 收集器,然后再继续。 一种这样的情况是当用户在接受治疗之前即将离开时。 在离开之前,您可以显式调用返回承诺的 publish() 方法。

await context.publish().then(() => {
    window.location = "https://www.absmartly.com"
})

Finalizing

finalize() 方法将确保所有事件都已发布到 A/B Smartly 收集器,如 publish(),并且还将“密封”上下文,抛出一个如果调用任何可以生成事件的方法,则出错。

await context.finalize().then(() => {
    window.location = "https://www.absmartly.com"
})

Refreshing the context with fresh experiment data

对于长时间运行的单页应用程序 (SPA),上下文通常在首次访问应用程序时创建一次。 但是,在您的生产代码中跟踪但在创建上下文之后开始的任何实验都不会被触发。 为了缓解这种情况,我们可以在创建上下文时使用 refreshInterval 选项。

const request = {
    units: {
        session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
    },
};

const context = sdk.createContext(request, {
    refreshInterval: 5 * 60 * 1000
});

或者,可以手动调用 refresh() 方法。 refresh() 方法从 A/B Smartly 收集器中提取更新的实验数据,并在再次调用 treatment() 时触发最近开始的实验。

setTimeout(async () => {
    try {
        context.refresh();
    } catch(error) {
        console.error(error);
    }
}, 5 * 60 * 1000);

Using a custom Event Logger

A/B Smartly SDK 可以使用用于所有上下文的事件记录器进行实例化。 此外,在创建特定上下文时,可以在 createContext 调用选项中指定事件记录器。 下面的示例通过默认事件记录器的实现说明了这一点,如果没有指定则使用。

const sdk = new absmartly.SDK({
    endpoint: 'https://sandbox-api.absmartly.com/v1',
    apiKey: process.env.ABSMARTLY_API_KEY,
    environment: process.env.NODE_ENV,
    application: process.env.APPLICATION_NAME,
    eventLogger: (context, eventName, data) => {
        if (eventName == "error") {
            console.error(data);
        }
    },
});

数据参数取决于事件的类型。 目前,SDK 记录以下事件:

eventNamewhendata
"error"Context receives an errorerror object thrown
"ready"Context turns readydata used to initialize the context
"refresh"Context.refresh() method succeedsdata used to refresh the context
"publish"Context.publish() method succeedsdata sent to the A/B Smartly event collector
"exposure"Context.treatment() method succeeds on first exposureexposure data enqueued for publishing
"goal"Context.track() method succeedsgoal data enqueued for publishing
"finalize"Context.finalize() method succeeds the first timeundefined

Peek at treatment variants

虽然通常不推荐,但有时需要在不触发曝光的情况下偷看治疗。 A/B Smartly SDK 为此提供了一个 peek() 方法。

if (context.peek("exp_test_experiment") == 0) {
    // user is in control group (variant 0)
} else {
    // user is in treatment group
}

Overriding treatment variants

例如,在开发过程中,强制进行实验处理很有用。 这可以通过 override() 和/或 overrides() 方法来实现。 override()overrides() 方法可以在上下文准备好之前调用。

    context.override("exp_test_experiment", 1); // force variant 1 of treatment
    context.overrides({
        exp_test_experiment: 1,
        exp_another_experiment: 0,
    });

HTTP request timeout

可以为每个单独的 HTTP 请求设置超时,在实例化 SDK 对象时覆盖为所有请求设置的全局超时。

下面是一个仅为 createContext 请求设置超时的示例。

const context = sdk.createContext(request, {
    refreshInterval: 5 * 60 * 1000
}, {
    timeout: 1500
});

HTTP Request cancellation

有时取消飞行中的 HTTP 请求很有用,例如,当用户离开时。 A/B Smartly SDK 还支持通过 AbortSignal 取消。 为旧平台提供了 AbortController 的实现,但将在可用的情况下使用本机实现。

以下是取消场景的示例。

const controller = new absmartly.AbortController();
const context = sdk.createContext(request, {
    refreshInterval: 5 * 60 * 1000
}, {
    signal: controller.signal
});

// abort request if not ready after 1500ms
const timeoutId = setTimeout(() => controller.abort(), 1500);

await context.ready();

clearTimeout(timeoutId);

About A/B Smartly

A/B Smartly 是一流的本地全堆栈实验平台的领先提供商,面向希望在开发过程中尽快自信地部署功能的工程和产品团队他们。 A/B Smartly 的实时分析可帮助工程和产品团队确保新功能将改善客户体验,而不会破坏或降低性能和/或业务指标。

Have a look at our growing list of clients and SDKs:

A/B Smartly SDK npm version

A/B Smartly - JavaScript SDK

Compatibility

The A/B Smartly Javascript SDK is an isomorphic library for Node.js (CommonJS and ES6) and browsers (UMD).

It's supported on Node.js version 6.x and npm 3.x or later.

It's supported on IE 10+ and all the other major browsers.

Note: IE 10 does not natively support Promises. If you target IE 10, you must include a polyfill like es6-promise or rsvp.

Installation

npm

npm install @absmartly/javascript-sdk --save

Import in your Javascript application

const absmartly = require('@absmartly/javascript-sdk');
// OR with ES6 modules:
import absmartly from '@absmartly/javascript-sdk';

Directly in the browser

You can include an optimized and pre-built package directly in your HTML code through unpkg.com.

Simply add the following code to your head section to include the latest published version.

    <script src="https://unpkg.com/@absmartly/javascript-sdk/dist/absmartly.min.js"></script>

Getting Started

Please follow the installation instructions before trying the following code:

Initialization

This example assumes an Api Key, an Application, and an Environment have been created in the A/B Smartly web console.

// somewhere in your application initialization code
const sdk = new absmartly.SDK({
    endpoint: 'https://sandbox.absmartly.io/v1',
    apiKey: process.env.ABSMARTLY_API_KEY,
    environment: process.env.NODE_ENV,
    application: process.env.APPLICATION_NAME,
});

Creating a new Context with raw promises

// define a new context request
const request = {
    units: {
        session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
    },
};

// create context with raw promises
const context = sdk.createContext(request);

context.ready().then((response) => {
    console.log("ABSmartly Context ready!")
}).catch((error) => {
    console.log(error);
});

Creating a new Context with async/await

// define a new context request
const request = {
    units: {
        session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
    },
};

// create context with raw promises
const context = sdk.createContext(request);

try {
    await context.ready();
    console.log("ABSmartly Context ready!")
} catch (error) {
    console.log(error);
}

Creating a new Context with pre-fetched data

When doing full-stack experimentation with A/B Smartly, we recommend creating a context only once on the server-side. Creating a context involves a round-trip to the A/B Smartly event collector. We can avoid repeating the round-trip on the client-side by sending the server-side data embedded in the first document, for example, by rendering it on the template. Then we can initialize the A/B Smartly context on the client-side directly with it.

    <head>
        <script type="javascript">
            const request = {
                units: {
                    session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
                },
            };

            const context = sdk.createContextWith(request, {{ serverSideContext.data() }});
        </script>
    </head>

Setting context attributes

The attribute() and attributes() methods can be called before the context is ready.

context.attribute('user_agent', navigator.userAgent);

context.attributes({
    customer_age: 'new_customer',
});

Selecting a treatment

if (context.treament("exp_test_experiment") == 0) {
    // user is in control group (variant 0)
} else {
    // user is in treatment group
}

Tracking a goal achievement

Goals are created in the A/B Smartly web console.

context.track("payment", { item_count: 1, total_amount: 1999.99 });

Publishing pending data

Sometimes it is necessary to ensure all events have been published to the A/B Smartly collector, before proceeding. One such case is when the user is about to navigate away right before being exposed to a treatment. You can explicitly call the publish() method, which returns a promise, before navigating away.

await context.publish().then(() => {
    window.location = "https://www.absmartly.com"
})

Finalizing

The finalize() method will ensure all events have been published to the A/B Smartly collector, like publish(), and will also "seal" the context, throwing an error if any method that could generate an event is called.

await context.finalize().then(() => {
    window.location = "https://www.absmartly.com"
})

Refreshing the context with fresh experiment data

For long-running single-page-applications (SPA), the context is usually created once when the application is first reached. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered. To mitigate this, we can use the refreshInterval option when creating the context.

const request = {
    units: {
        session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8',
    },
};

const context = sdk.createContext(request, {
    refreshInterval: 5 * 60 * 1000
});

Alternatively, the refresh() method can be called manually. The refresh() method pulls updated experiment data from the A/B Smartly collector and will trigger recently started experiments when treatment() is called again.

setTimeout(async () => {
    try {
        context.refresh();
    } catch(error) {
        console.error(error);
    }
}, 5 * 60 * 1000);

Using a custom Event Logger

The A/B Smartly SDK can be instantiated with an event logger used for all contexts. In addition, an event logger can be specified when creating a particular context, in the createContext call options. The example below illustrates this with the implementation of the default event logger, used if none is specified.

const sdk = new absmartly.SDK({
    endpoint: 'https://sandbox-api.absmartly.com/v1',
    apiKey: process.env.ABSMARTLY_API_KEY,
    environment: process.env.NODE_ENV,
    application: process.env.APPLICATION_NAME,
    eventLogger: (context, eventName, data) => {
        if (eventName == "error") {
            console.error(data);
        }
    },
});

The data parameter depends on the type of event. Currently, the SDK logs the following events:

eventNamewhendata
"error"Context receives an errorerror object thrown
"ready"Context turns readydata used to initialize the context
"refresh"Context.refresh() method succeedsdata used to refresh the context
"publish"Context.publish() method succeedsdata sent to the A/B Smartly event collector
"exposure"Context.treatment() method succeeds on first exposureexposure data enqueued for publishing
"goal"Context.track() method succeedsgoal data enqueued for publishing
"finalize"Context.finalize() method succeeds the first timeundefined

Peek at treatment variants

Although generally not recommended, it is sometimes necessary to peek at a treatment without triggering an exposure. The A/B Smartly SDK provides a peek() method for that.

if (context.peek("exp_test_experiment") == 0) {
    // user is in control group (variant 0)
} else {
    // user is in treatment group
}

Overriding treatment variants

During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the override() and/or overrides() methods. The override() and overrides() methods can be called before the context is ready.

    context.override("exp_test_experiment", 1); // force variant 1 of treatment
    context.overrides({
        exp_test_experiment: 1,
        exp_another_experiment: 0,
    });

HTTP request timeout

It is possible to set a timeout per individual HTTP request, overriding the global timeout set for all request when instantiating the SDK object.

Here is an example of setting a timeout only for the createContext request.

const context = sdk.createContext(request, {
    refreshInterval: 5 * 60 * 1000
}, {
    timeout: 1500
});

HTTP Request cancellation

Sometimes it is useful to cancel an inflight HTTP request, for example, when the user is navigating away. The A/B Smartly SDK also supports a cancellation via an AbortSignal. An implementation of AbortController is provided for older platforms, but will use the native implementation where available.

Here is an example of a cancellation scenario.

const controller = new absmartly.AbortController();
const context = sdk.createContext(request, {
    refreshInterval: 5 * 60 * 1000
}, {
    signal: controller.signal
});

// abort request if not ready after 1500ms
const timeoutId = setTimeout(() => controller.abort(), 1500);

await context.ready();

clearTimeout(timeoutId);

About A/B Smartly

A/B Smartly is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them. A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.

Have a look at our growing list of clients and SDKs:

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文