Téléchargement, stockage et mise à jour de l’artefact de règle via la charge utile JSON
- Rubriques :
- APIs/SDKs
Créé pour :
- Développeur
Cette approche est préférable si votre application est structurée de manière à ce que le SDK soit initialisé sur chaque fichier dans lequel il utilise des méthodes SDK. Avant que votre application web puisse utiliser la charge utile JSON de l’artefact de règle lors de l’initialisation du SDK, vous devez vous assurer que la charge utile JSON est téléchargée et disponible pour que votre application l’utilise.
Résumé des étapes
- Installation du SDK
- Initialisation du SDK
- Stocker et utiliser la charge utile JSON
1. Installation du SDK
npm i @adobe/target-nodejs-sdk -P
<dependency>
<groupId>com.adobe.target</groupId>
<artifactId>java-sdk</artifactId>
<version>1.0</version>
</dependency>
2. Initialisation du SDK
-
Importez tout d’abord le SDK. Importez dans le fichier à partir duquel vous pouvez contrôler le démarrage de votre serveur.
Node.js
const TargetClient = require("@adobe/target-nodejs-sdk");
Java
import com.adobe.target.edge.client.ClientConfig; import com.adobe.target.edge.client.TargetClient;
-
Pour configurer le SDK, utilisez la méthode create .
Node.js
const CONFIG = { client: "<your target client code>", organizationId: "your EC org id", decisioningMethod: "on-device", pollingInterval : 300000, events: { artifactDownloadSucceeded: onArtifactDownloadSucceeded, artifactDownloadFailed: onArtifactDownloadFailed } }; const TargetClient = TargetClient.create(CONFIG); function onArtifactDownloadSucceeded(event) { //Adobe Target SDK has now downloaded the JSON Artifact/Payload console.log(event.artifactLocation) // Location from where the Artifact is downloaded. console.log(event.artifactPayload) // JSON Payload which we can store locally. } function onArtifactDownloadFailed(event) { //Adobe Target SDK has failed to download the JSON Artifact/Payload. console.log(event.artifactLocation) // Location from where the Artifact is downloaded. console.log(event.error.message) // Error message }
Java
package com.adobe.target.edge.client.model.ondevice.OnDeviceDecisioningHandler; ClientConfig config = ClientConfig.builder() .client("<you target client code>") .organizationId("<your EC org id>") .onDeviceDecisioningHandler( new OnDeviceDecisioningHandler() { void onDeviceDecisioningReady() { // On-Device Decision is ready. } void artifactDownloadSucceeded(byte[] artifactData) { // Store artifactData to local disk. // ... } } ) .build(); TargetClient targetClient = TargetClient.create(config);
-
Le client et
organizationId
peuvent être récupérés à partir de Adobe Target en accédant à Administration > Implementation, comme illustré ici.<!— Insérer image-client-code.png —>
3. Stocker et utiliser à nouveau la charge utile JSON
Le mécanisme que vous utilisez pour stocker la charge utile JSON dépend de l’architecture de votre système. Vous pouvez utiliser un fichier local, une base de données ou un système de mise en cache d’objets mémoire, tel que Memcached. Vous devez être en mesure de lire ce fichier JSON à partir de votre application à des fins d’utilisation. Dans ce guide, nous utilisons un fichier local comme stockage.
//... Code removed for brevity
function onArtifactDownloadSucceeded(event) {
const jsonPath = 'src/config/target-rules.json'
fs.writeFile(jsonPath, JSON.stringify(event.artifactPayload), 'utf8', (err) => {
if (err) {
throw err;
};
console.log(`The artifact from '${event.artifactLocation}' is now saved to '${jsonPath}'`);
});
}
function onArtifactDownloadFailed(event) {
console.log(`The local decisioning artifact failed to download from '${event.artifactLocation}' with the following error message: ${event.error.message}`);
}
//... Code removed for brevity
MboxRequest mbox = new MboxRequest().name("homepage").index(0);
TargetDeliveryRequest request = TargetDeliveryRequest.builder()
.context(new Context().channel(ChannelType.WEB))
.execute(new ExecuteRequest().mboxes(Arrays.asList(mbox)))
.build();
TargetDeliveryResponse response = targetClient.getOffers(request);
Voici un exemple illustrant la fonctionnalité d’initialisation de la payload JSON.
const express = require("express");
const cookieParser = require("cookie-parser");
const TargetClient = require("@adobe/target-nodejs-sdk");
const CONFIG = {
client: "<your target client code>",
organizationId: "your EC org id",
decisioningMethod: "on-device",
pollingInterval : 300000,
events: {
clientReady : startWebServer,
artifactDownloadSucceeded : onArtifactDownloadSucceeded,
artifactDownloadFailed : onArtifactDownloadFailed
},
};
function onArtifactDownloadSucceeded(event) {
const jsonPath = 'src/config/target-rules.json'
fs.writeFile(jsonPath, JSON.stringify(event.artifactPayload), 'utf8', (err) => {
if (err) {
throw err;
};
console.log(`The artifact from '${event.artifactLocation}' is now saved to '${jsonPath}'`);
});
}
function onArtifactDownloadFailed(event) {
console.log(`The on-device decisioning artifact failed to download from '${event.artifactLocation}' with the following error message: ${event.error.message}`);
}
const app = express();
const targetClient = TargetClient.create(CONFIG);
app.use(cookieParser());
function saveCookie(res, cookie) {
if (!cookie) {
return;
}
res.cookie(cookie.name, cookie.value, {maxAge: cookie.maxAge * 1000});
}
const getResponseHeaders = () => ({
"Content-Type": "text/html",
"Expires": new Date().toUTCString()
});
function sendSuccessResponse(res, response) {
res.set(getResponseHeaders());
saveCookie(res, response.targetCookie);
res.status(200).send(response);
}
function sendErrorResponse(res, error) {
res.set(getResponseHeaders());
res.status(500).send(error);
}
function startWebServer() {
app.get('/*', async (req, res) => {
const targetCookie = req.cookies[TargetClient.TargetCookieName];
const request = {
execute: {
mboxes: [{
address: { url: req.headers.host + req.originalUrl },
name: "on-device-homepage-banner" // Ensure that you have a LIVE Activity running on this location
}]
}};
try {
const response = await targetClient.getOffers({ request, targetCookie });
sendSuccessResponse(res, response);
} catch (error) {
console.error("Target:", error);
sendErrorResponse(res, error);
}
});
app.listen(3000, function () {
console.log("Listening on port 3000 and watching!");
});
}
import com.adobe.target.edge.client.ClientConfig;
import com.adobe.target.edge.client.TargetClient;
import com.adobe.target.delivery.v1.model.ChannelType;
import com.adobe.target.delivery.v1.model.Context;
import com.adobe.target.delivery.v1.model.ExecuteRequest;
import com.adobe.target.delivery.v1.model.MboxRequest;
import com.adobe.target.edge.client.entities.TargetDeliveryRequest;
import com.adobe.target.edge.client.model.TargetDeliveryResponse;
@Controller
public class TargetController {
private TargetClient targetClient;
TargetController() {
// You should instantiate TargetClient in a Bean and inject the instance into this class
// but we show the code here for demonstration purpose.
ClientConfig config = ClientConfig.builder()
.client("<you target client code>")
.organizationId("<your EC org id>")
.onDeviceDecisioningHandler(
new OnDeviceDecisioningHandler() {
void onDeviceDecisioningReady() {
// On-Device Decision is ready.
}
void artifactDownloadSucceeded(byte[] artifactData) {
// Store artifactData to local disk.
// ...
}
}
)
.build();
targetClient = TargetClient.create(config);
}
@GetMapping("/")
public String homePage() {
MboxRequest mbox = new MboxRequest().name("homepage").index(0);
TargetDeliveryRequest request = TargetDeliveryRequest.builder()
.context(new Context().channel(ChannelType.WEB))
.execute(new ExecuteRequest().mboxes(Arrays.asList(mbox)))
.build();
TargetDeliveryResponse response = targetClient.getOffers(request);
// ...
}
}