1.0.0-alpha.4 • Published 11 months ago

@taggstar/nodejs-sdk v1.0.0-alpha.4

Weekly downloads
-
License
ISC
Repository
-
Last release
11 months ago

Taggstar NodeJS SDK

The Taggstar NodeJS SDK is a library that simplifies interaction with the authorized Taggstar API.

Installation

Install via npm:

npm install @taggstar/nodejs-sdk

Basic Usage

This is the basic useage of Taggstar NodeJS SDK. After you've created the TaggstarNodeJSSDK instance, you can start invoking methods to get social prrof messages/recommended products or to notify an order or an event (eg add to basket) to Taggstar API.

import { TaggstarNodeJSSDK } from "@taggstar/nodejs-sdk";

const nodejsSDK = new TaggstarNodeJSSDK(
  "<Your-Access-Key-ID>",
  "<Your-Secret-Access-Key>"
);

Then you create a visitor instance with a default storage provider and post a category request which returns social proof messages for the product list.

app.get("/category", async (req, res) => {
  try {

    // Create a default storage provider
    const storageProvider = nodejsSDK.createDefaultStorageProvider(req, res);

    // Get the visitor entity
    const visitor = nodejsSDK.getVisitor(site, storageProvider);

    // Post the category data
    const data = await visitor.postCategory({ category, products: productIds }, options);

    res.json(data);
  } catch (error: any) {
    res.status(error?.response?.status || 500).json(error);
  }
});

Custom Configuration

The previous section covered basic installation and usage of the NodeJS SDK with default settings for configuration. But sometimes you may need to customize these defaults.

Constructor

import { TaggstarNodeJSSDK } from "@taggstar/nodejs-sdk";

const nodejsSDK = new TaggstarNodeJSSDK(
  accessKeyId,
  secretAccessKey,
  configuration
);

Parameters

accessKeyId required

  • TypeString
  • Description — A public key that is defined for the sitekey
  • Default — N/A

secretAccessKey required

  • TypeString
  • Description — A private key that is defined for the sitekey
  • Default — N/A

configuration optional

  • TypeObject
  • Description — Defines environment and detail response object settings
  • Default — The following shows the default values for configuration.
// This is the default configuration object
const config = {
  detail: false, // no detail object returned in response
  environment: "prod", // "prod" or "qa"
};

User Entity

The UserEntity serves as a central, high-level entity that bridges your application to the underlying functionalities provided by our SDK. It offers a set of methods that allow comprehensive interaction with different user-related facets within your system.

Get Visitor

Creating a UserEntity simplifies any iteraction with Taggstar API. TaggstarNodeJSSDK instance provides getVisitor method to create/get the session of an anonymous user.

const visitor = nodejsSDK.getVisitor(site, storageProvider);

Parameters

site required

  • TypeObject
  • Description — Defines site key and if provided region and test provider settings
  • Default — N/A
const site = {
  key: "demo-site-key",
  region: "eu-west-1", // optional. Default value is "eu-west-1". Other option is "us-east-2", Defines the region information.
  socialProofTestProvider: "server", // optional. Default value is "server". Defines who is provider for A/B test of social proof experiments. Other option is "client"
  recsTestProvider: "server", // optional. Default value is "server". Defines who is provider for A/B test of recs experiments. Other option is "client"
};

storageProvider required

  • TypeObject
  • Description — Defines storage provider for getting visitor session and getting/saving experiment id/group info when Taggstar is A/B test provider
  • Default — N/A

Default Storage Provider

TaggstarNodeJSSDK instance provides createDefaultStorageProvider method that can be used on ExpressJS for storage of visitor session data (visitor id and sessionId) and experiment data(id and group) on browser cookies of the user subject to the request. This method returns an object which provides functions handle getting and saving related data.

const storageProvider = nodejsSDK.createDefaultStorageProvider(
  req,
  res,
  option
);

Parameters

req required

  • TypeObject
  • Description — ExpressJS Request object
  • Default — N/A

res required

  • TypeObject
  • Description — ExpressJS Response object
  • Default — N/A

option optional

  • TypeObject
  • Description — Defines settings for cookie domain and path
  • Default — The following shows default values for option
const option = {
  cookieDomain: "<The URI for which the Cookie is valid>",
  cookiePath: "/",
};

Custom Storage Provider

If you wish to implement your own custom storage provider for the SDK, your storage provider should be an object that includes the following methods:

getVisitor()

This method should be asynchronous and when called, it should return a Promise that resolves with a Visitor object.

// An example of a 'Visitor" object returned by getVisitor() method
const returnedVisitor = {
  visitorId: "<Visitor Id>",
  sessionId: "<Session Id>",
};

getSocialProofExperiment()

This method is optional. It should be implemented when site.socialProofTestProvider == "server". If implemented, it should be asynchronous and when called, it should return a Promise that resolves with an Experiment object if it exists, or undefined.

// An example of a 'Experiment" object returned by getSocialProofExperiment() method
const returnedExperiment = {
  id: "<Experiment Id>",
  group: "<Experiment Group>",
};

saveSocialProofExperiment(experiment)

This method is optional. It should be implemented when site.socialProofTestProvider == "server". If implemented, it should be asynchronous and accept an Experiment object as an argument. When called, it should save the experiment and return a Promise that resolves with an object that indicates the status of the operation.

experiment required

  • TypeObject
  • Description — Defines experiment id and group info
  • Default — N/A
saveSocialProofExperiment({
  id: "<Experiment Id>",
  group: "<Experiment Group>",
}).then(function(result) {
  console.log("Successfully saved!")l
}).catch(function(err) {
  console.log("Error!");
});

getRecsExperiment()

This method is optional. It should be implemented when site.recsTestProvider == "server". If implemented, it should be asynchronous and when called, it should return a Promise that resolves with an Experiment object if it exists, or undefined.

saveRecsExperiment(experiment)

This method is optional. It should be implemented when site.recsTestProvider == "server". If implemented, it should be asynchronous and accept an Experiment object as an argument. When called, it should save the experiment and return a Promise that resolves with an object that indicates the status of the operation.

Here's the TypeScript interface for reference:

export interface StorageProvider<T> {
  getVisitor(): Promise<Visitor>;
  getUser?(): Promise<User>;
  getSocialProofExperiment?(): Promise<Experiment | undefined>;
  saveSocialProofExperiment?(experiment: Experiment): Promise<T>;
  getRecsExperiment?(): Promise<Experiment | undefined>;
  saveRecsExperiment?(experiment: Experiment): Promise<T>;
}

POST Category

UserEntity provides postCategory method to send a list of product Ids (plus category name) and returns social proof messages for each product if exist. An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .postCategory(categoryJson, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

categoryJson required

  • TypeObject
  • Description — Defines product id list and the name of category
  • Default — N/A

This is an example of categoryJson object:

const categoryJson = {
  category: "/my category/my sub category", // optional. Defines category as a string. Default value is "-"
  products: ["p1", "p2", "p3"], // required. Defines list of products as an array of strings.
};

options: See Options Parameter section for details.

POST Product

UserEntity provides postProduct method to send a product object and returns social proof messages for that product if exist. An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .postProduct(product, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

product required

  • TypeObject
  • Description — Defines a product object
  • Default — N/A

This is an example of product obkect:

const product = {
  id: "p1", // required. Defines product id as a string
  name: "<product name>", // optional. Defines product name as a string
  price: 12.0, // optional. Defines product price as a number
  category: "<product category>", // optional. Defines product category as a string
  variant: {
    "<variant key>": "<variant value>", // eg. size: "UK 8"
  }, // required when LSQ message codes are defined in rule config. Defines a product variant as an object
  stock: [
    {
      quantity: 2, // required. stock number for specified variant
      variant: {
        "<variant key>": "<variant value>",
      },
    }, // required when LSQ message codes are defined in rule config. Defines array of product variant and quantity objects
  ],
};

options: See Options Parameter section for details.

POST Basket

UserEntity provides postBasket method to send a list of basket items and returns social proof messages for each product if exist. An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .postBasket(basket, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

basket required

  • TypeObject
  • Description — Defines a basket object
  • Default — N/A

This is an example of basket object:

const basket = {
  lineItems: [
    {
      id: "p1", // required. Defines product id as a string
      quantity: 2, // required. Defines product quantity as a number
      price: 12.0, // required. Defines product price as a number
      category: "<product category>", // optional. Defines product category as a string
      variant: {
        "<variant key>": "<variant value>", // eg. size: "UK 8"
      }, // required when LSQ message codes are defined in rule config. Defines a product variant as an object
      stock: [
        {
          quantity: 2, // required. stock number for specified variant
          variant: {
            "<variant key>": "<variant value>",
          },
        }, // required when LSQ message codes are defined in rule config. Defines array of product variant and quantity objects
      ],
    },
    {
      // Second item
    },
  ],
};

options: See Options Parameter section for details.

POST Conversion

UserEntity provides postConversion method to send a list of order items and order meta data (eg orderId, currency, totalPrice). An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .postConversion(order, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

order required

  • TypeObject
  • Description — Defines a order object
  • Default — N/A

This is an example of order object:

const order = {
  id: "<order id>", // required. Defines order id as a string
  currency: "<currency>", // required. Defines currency as a string. Eg GBP
  totalPrice: 36.5, // required. Defines order total price as a number
  orderItems: [
    {
      id: "p1", // required. Defines product id as a string
      quantity: 2, // required. Defines product quantity as a number
      price: 12.0, // required. Defines product price as a number
      category: "<product category>", // optional. Defines product category as a string
    },
    {
      // Second item
    },
  ],
};

options: See Options Parameter section for details.

POST Recs

UserEntity provides postRecs method to send a recommendation object and returns product lists relates to algorithms with social proof messages for that product if exist. An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .postRecs(recs, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

recs required

  • TypeObject
  • Description — Defines a recs object
  • Default — N/A

This is an example of recs obkect:

const recs = {
  category: "<category name>", // optional
  productIds: ["p1", "p2", "p3"], // otional. array of product ids
  page: {
    type: "<page type>", // required. Defines page type of string
    id: "<page id>", // optional, Defines page id of string
  },
};

options: See Options Parameter section for details.

POST Event

UserEntity provides postEvent method to send an event eg "add to basket". An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .postEvent(event, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

event required

  • TypeObject
  • Description — Defines an event object
  • Default — N/A

This is an example of event obkect:

const event = {
  category: "<category name>", // required. Defines category name as string
  name: "<event name>", // required. Defines event name as string
  data: {
    label: "<event data label>", // required. Defines event data label as string
    value: "<event data value>", // optional. Defines event data value as any primitive type
  },
  eventGroupId: "<event name>", // optional. Defines parent event group id as string
};

options: See Options Parameter section for details.

POST Event Query

UserEntity provides postEventQuery method to send an event query. An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .postEventQuery(eventQuery, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

eventQuery required

  • TypeObject
  • Description — Defines an eventQuery object
  • Default — N/A

This is an example of eventQuery obkect:

const eventQuery = {
  category: "<category name>", // required. Defines category name as string
  name: "<event name>", // required. Defines event query name as string
  window: "<window length>", // required. Defines event query window as string
  select: "<event query select>", // required. Defines event query select as string
};

options: See Options Parameter section for details.

GET Products

UserEntity provides getProducts method to send a list of product Ids and returns social proof messages for each product if exist. An example below display how it is used:

// visitor object created by getVisitor method
visitor
  .getProducts(productIds, options)
  .then((data) => {
    console.log(data);
  })
  .catch((err) => {
    console.log(err);
  });

Parameters

productIds required

  • TypeArray
  • Description — Defines product id list
  • Default — N/A

options: See Options Parameter section for details.

Options Parameter

This parameter is a common parameter for all UserEntity methods

options optional

  • TypeObject
  • Description — Defines client, experience (if site.socialProofTestProvider == "client") and debugParams
  • Default — N/A

This is an example of options parameter:

const options = {
  client: {
    deviceType: "desktop", // optional. Default value is "desktop". Other options are "tablet", "mobile" and "application", Defines the device type information.
    locale: "en-GB", // optional. Default value is defined in site config.
  },
  experience: {
    id: "experience-v1", // required when site.socialProofTestProvider == "client". This is the experience id for 3rd party test providers.
  },
  // optional. If set, dimensions will be used only for postConversion method.
  experiences: {
    // used when site.socialProofTestProvider == "client". This is the experience id for 3rd party test providers.
    socialProof: {
      id: "<social proof experience id>",
    },
    // used when site.recsTestProvider == "client". This is the experience id for 3rd party test providers.
    recs: {
      id: "<recs experience id>",
    },
  },
  dimensions: {
    // optional. If set, dimensions will be used only for postConversion method.
    dim1: "<dim1 value>",
    dim2: "<dim1 value>",
    dim3: "<dim1 value>",
  },
  debugParams: {
    // debugParams object is used for any debug purposes. All of them are optional
    fakeData: ["CAP", "QP"], // array of message codes. Returns fake messages for a product
    deviceType: "mobile", // fake device type. Available values are same as client.deviceType
    experienceId: "test-experience-id", // cannot be set if experimentId/experimentGroup is already set
    experimentId: "draft-experiment-id", // cannot be set if experinceId is already set and can be used with experimentGroup
    experimentGroup: "draft-experiment-group", // cannot be set if experinceId is already set and can be used with experimentID
    returnDebugObject: true, // adds e debug object same as detail object to the repsonse
  },
};

Warning about debugParams. Be careful not to forget to remove this object before releasing your code to PRODUCTION env.

1.0.0-alpha.4

11 months ago

1.0.0-alpha.3

11 months ago

1.0.0-alpha.2

11 months ago

1.0.0-alpha.1

11 months ago

1.0.0-alpha.0

11 months ago