Skip to content

Commit 17641af

Browse files
committed
Fixes based on review
1 parent 10b813a commit 17641af

File tree

8 files changed

+54
-133
lines changed

8 files changed

+54
-133
lines changed

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
"license": "ISC",
2727
"dependencies": {
2828
"@optimizely/optimizely-sdk": "^4.9.1",
29-
"node-fetch": "^3.2.6"
29+
"cookie": "^0.5.0"
3030
},
3131
"devDependencies": {
3232
"@rollup/plugin-commonjs": "^22.0.0",
@@ -36,4 +36,4 @@
3636
"rollup-plugin-copy": "^3.4.0",
3737
"rollup-plugin-terser": "^7.0.2"
3838
}
39-
}
39+
}

rollup.config.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
1-
import resolve from '@rollup/plugin-node-resolve';
1+
import { nodeResolve } from '@rollup/plugin-node-resolve';
22
import commonjs from '@rollup/plugin-commonjs';
33
import copy from 'rollup-plugin-copy';
44
import json from '@rollup/plugin-json';
55
import { terser } from 'rollup-plugin-terser';
66

77
export default {
88
input: 'src/index.js',
9-
external: ['log', 'http-request', 'cookies'],
109
output: {
1110
format: 'es',
1211
dir: 'dist',
1312
},
1413
preserveModules: false,
1514
plugins: [
15+
nodeResolve({ browser: true }),
1616
commonjs(),
1717
json(),
18-
resolve({ browser: true }),
1918
copy({
2019
targets: [
2120
{

src/cookies.js

Lines changed: 0 additions & 58 deletions
This file was deleted.

src/index.js

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import {
22
createInstance,
33
enums as OptimizelyEnums,
44
} from '@optimizely/optimizely-sdk/dist/optimizely.lite.es';
5-
import { getCookie, setHeaderCookie } from './cookies';
5+
6+
import * as cookie from 'cookie';
67

78
import {
89
dispatchEvent,
@@ -36,8 +37,10 @@ exports.handler = async (event, _context, callback) => {
3637
}
3738

3839
let headers = {};
40+
let cookies = {};
3941
try {
4042
headers = request.headers;
43+
cookies = headers.cookie;
4144
} catch (error) {
4245
console.log(
4346
'[OPTIMIZELY] WARNING: Unable to get headers object from request object. This may be because the event is not a CloudFront event.'
@@ -47,14 +50,14 @@ exports.handler = async (event, _context, callback) => {
4750
try {
4851
// 1. User ID: Get the user ID from the cookie if it exists - otherwise generate a new user ID.
4952
console.log('[OPTIMIZELY] Getting user ID...');
50-
let userId = getCookie(headers, COOKIE_NAME_OPTIMIZELY_USER_ID);
53+
let userId = cookies[COOKIE_NAME_OPTIMIZELY_USER_ID] || '';
5154

52-
if (!userId) {
55+
if (userId === '') {
5356
userId = generateRandomUserId();
54-
headers = setHeaderCookie(
55-
headers,
56-
`${COOKIE_NAME_OPTIMIZELY_USER_ID}=${userId}`
57-
);
57+
headers = {
58+
...headers,
59+
'Set-Cookie': cookie.serialize(COOKIE_NAME_OPTIMIZELY_USER_ID, userId),
60+
};
5861
}
5962

6063
console.log(`[OPTIMIZELY] Using User ID: ${userId}`);
@@ -77,12 +80,12 @@ exports.handler = async (event, _context, callback) => {
7780
* Optional event dispatcher. Please uncomment the following line if you want to dispatch an impression event to optimizely logx backend.
7881
* When enabled, an event is dispatched asynchronously. It does not impact the response time for a particular worker but it may
7982
* add to the total compute time of the Lambda function and can impact AWS billing.
80-
*
83+
*
8184
* The event dispatcher attached below is a sample implementation of fire-and-forget event dispatching
8285
* in Lambda, however if your needs are more complex, you can implement your own event dispatcher
8386
* and integrate with Step Functions, SQS, or other services.
8487
*/
85-
// eventDispatcher: dispatchEvent,
88+
// eventDispatcher: { dispatchEvent },
8689
});
8790

8891
// 4. Experimentation Logic: Get a specific experiment result for this particular User ID.
@@ -106,7 +109,8 @@ exports.handler = async (event, _context, callback) => {
106109
// === For a Single Flag === //
107110
const decision = optimizelyUserContext.decide('<YOUR_FLAG_HERE>'); // TODO: Replace with your flag name.
108111
console.log(
109-
`[OPTIMIZELY] The Flag ${decision.flagKey} was ${decision.enabled ? 'Enabled' : 'Not Enabled'
112+
`[OPTIMIZELY] The Flag ${decision.flagKey} was ${
113+
decision.enabled ? 'Enabled' : 'Not Enabled'
110114
} for the user ${decision.userContext.getUserId()}`
111115
);
112116

@@ -134,7 +138,10 @@ exports.handler = async (event, _context, callback) => {
134138
// 5. Result: Return the result to the caller via appending headers or cookies to the callback function.
135139

136140
// 5a. Cookies
137-
// headers = setHeaderCookie(headers, `${COOKIE_NAME_OPTIMIZELY_USER_ID}=${userId}`);
141+
// headers = {
142+
// ...headers,
143+
// 'Set-Cookie': cookie.serialize(COOKIE_NAME_OPTIMIZELY_USER_ID, userId)
144+
// }
138145

139146
// 5b. Headers
140147
// headers['<YOUR_FLAG_HERE>-decision'] = [

src/optimizely_helpers.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const https = require('https');
44
* generateRandomUserId - Generates a random user ID.
55
*
66
* Disclaimer:
7-
* It is recommnded to replace this user ID generator with your own method for production purposes.
7+
* It is recommended to replace this user ID generator with your own method for production purposes.
88
* Feel free to use this function at your own discretion.
99
*
1010
* @returns string
@@ -87,7 +87,8 @@ let _datafileLastFetchedTime = 0; // Note last time the datafile was fetched.
8787
/**
8888
* getDatafile - Retrieves the datafile from the Optimizely CDN.
8989
*
90-
* Note: This starter kit uses
90+
* Note: This starter kit uses in-memory caching per Lambda for data caching.
91+
* Alternative considerations could include using CloudFront or AWS S3 for caching instead.
9192
*
9293
* @param string sdkKey
9394
* @returns datafile JSON object

src/viewer_request.js

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ import {
22
createInstance,
33
enums as OptimizelyEnums,
44
} from '@optimizely/optimizely-sdk/dist/optimizely.lite.es';
5-
import { getCookie, setHeaderCookie } from './cookies';
5+
6+
import * as cookie from 'cookie';
67

78
import {
89
dispatchEvent,
@@ -36,8 +37,10 @@ exports.handler = async (event, _context, callback) => {
3637
}
3738

3839
let headers = {};
40+
let cookies = {};
3941
try {
4042
headers = request.headers;
43+
cookies = headers.cookie;
4144
} catch (error) {
4245
console.log(
4346
'[OPTIMIZELY] WARNING: Unable to get headers object from request object. This may be because the event is not a CloudFront event.'
@@ -47,14 +50,14 @@ exports.handler = async (event, _context, callback) => {
4750
try {
4851
// 1. User ID: Get the user ID from the cookie if it exists - otherwise generate a new user ID.
4952
console.log('[OPTIMIZELY] Getting user ID...');
50-
let userId = getCookie(headers, COOKIE_NAME_OPTIMIZELY_USER_ID);
53+
let userId = cookies[COOKIE_NAME_OPTIMIZELY_USER_ID] || '';
5154

52-
if (!userId) {
55+
if (userId === '') {
5356
userId = generateRandomUserId();
54-
headers = setHeaderCookie(
55-
headers,
56-
`${COOKIE_NAME_OPTIMIZELY_USER_ID}=${userId}`
57-
);
57+
headers = {
58+
...headers,
59+
'Set-Cookie': cookie.serialize(COOKIE_NAME_OPTIMIZELY_USER_ID, userId),
60+
};
5861
}
5962

6063
console.log(`[OPTIMIZELY] Using User ID: ${userId}`);
@@ -77,7 +80,7 @@ exports.handler = async (event, _context, callback) => {
7780
* Optional event dispatcher. Please uncomment the following line if you want to dispatch an impression event to optimizely logx backend.
7881
* When enabled, an event is dispatched asynchronously. It does not impact the response time for a particular worker but it may
7982
* add to the total compute time of the Lambda function and can impact AWS billing.
80-
*
83+
*
8184
* The event dispatcher attached below is a sample implementation of fire-and-forget event dispatching
8285
* in Lambda, however if your needs are more complex, you can implement your own event dispatcher
8386
* and integrate with Step Functions, SQS, or other services.
@@ -106,7 +109,8 @@ exports.handler = async (event, _context, callback) => {
106109
// === For a Single Flag === //
107110
const decision = optimizelyUserContext.decide('<YOUR_FLAG_HERE>'); // TODO: Replace with your flag name.
108111
console.log(
109-
`[OPTIMIZELY] The Flag ${decision.flagKey} was ${decision.enabled ? 'Enabled' : 'Not Enabled'
112+
`[OPTIMIZELY] The Flag ${decision.flagKey} was ${
113+
decision.enabled ? 'Enabled' : 'Not Enabled'
110114
} for the user ${decision.userContext.getUserId()}`
111115
);
112116

@@ -134,10 +138,10 @@ exports.handler = async (event, _context, callback) => {
134138
// 5. Result: Return the result to the caller via appending headers or cookies to the callback function.
135139

136140
// 5a. Cookies
137-
// headers = setHeaderCookie(
138-
// headers,
139-
// `${COOKIE_NAME_OPTIMIZELY_USER_ID}=${userId}`
140-
// );
141+
// headers = {
142+
// ...headers,
143+
// 'Set-Cookie': cookie.serialize(COOKIE_NAME_OPTIMIZELY_USER_ID, userId)
144+
// }
141145

142146
// 5b. Headers
143147
// headers['<YOUR_FLAG_HERE>-decision'] = [

src/viewer_response.js

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
* This will capture the generated userId cookie and return it to the client.
66
*/
77

8-
import { getCookie, setHeaderCookie } from './cookies';
8+
import * as cookie from 'cookie';
99

1010
const COOKIE_NAME_OPTIMIZELY_USER_ID = 'OPTIMIZELY_USER_ID';
1111

@@ -21,8 +21,10 @@ export function handler(event, _context, callback) {
2121
}
2222

2323
let headers = {};
24+
let cookies = {};
2425
try {
2526
headers = request.headers;
27+
cookies = headers.cookie;
2628
} catch (error) {
2729
console.log(
2830
'[OPTIMIZELY] WARNING: Unable to get headers object from request object. This may be because the event is not a CloudFront event.'
@@ -38,13 +40,13 @@ export function handler(event, _context, callback) {
3840
);
3941
}
4042

41-
const userId = getCookie(headers, COOKIE_NAME_OPTIMIZELY_USER_ID);
43+
const userId = cookies[COOKIE_NAME_OPTIMIZELY_USER_ID] || '';
4244

4345
if (userId != null) {
44-
response.headers = setHeaderCookie(
45-
headers,
46-
`${COOKIE_NAME_OPTIMIZELY_USER_ID}=${userId}`
47-
);
46+
response.headers = {
47+
...headers,
48+
'Set-Cookie': cookie.serialize(COOKIE_NAME_OPTIMIZELY_USER_ID, userId),
49+
};
4850
callback(null, response);
4951
return;
5052
}

yarn.lock

Lines changed: 4 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -298,10 +298,10 @@ concat-map@0.0.1:
298298
resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"
299299
integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==
300300

301-
data-uri-to-buffer@^4.0.0:
302-
version "4.0.0"
303-
resolved "https://registry.yarnpkg.com/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz#b5db46aea50f6176428ac05b73be39a57701a64b"
304-
integrity sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA==
301+
cookie@^0.5.0:
302+
version "0.5.0"
303+
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b"
304+
integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==
305305

306306
decompress-response@^4.2.1:
307307
version "4.2.1"
@@ -355,28 +355,13 @@ fastq@^1.6.0:
355355
dependencies:
356356
reusify "^1.0.4"
357357

358-
fetch-blob@^3.1.2, fetch-blob@^3.1.4:
359-
version "3.1.5"
360-
resolved "https://registry.yarnpkg.com/fetch-blob/-/fetch-blob-3.1.5.tgz#0077bf5f3fcdbd9d75a0b5362f77dbb743489863"
361-
integrity sha512-N64ZpKqoLejlrwkIAnb9iLSA3Vx/kjgzpcDhygcqJ2KKjky8nCgUQ+dzXtbrLaWZGZNmNfQTsiQ0weZ1svglHg==
362-
dependencies:
363-
node-domexception "^1.0.0"
364-
web-streams-polyfill "^3.0.3"
365-
366358
fill-range@^7.0.1:
367359
version "7.0.1"
368360
resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40"
369361
integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==
370362
dependencies:
371363
to-regex-range "^5.0.1"
372364

373-
formdata-polyfill@^4.0.10:
374-
version "4.0.10"
375-
resolved "https://registry.yarnpkg.com/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz#24807c31c9d402e002ab3d8c720144ceb8848423"
376-
integrity sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==
377-
dependencies:
378-
fetch-blob "^3.1.2"
379-
380365
fs-extra@^8.1.0:
381366
version "8.1.0"
382367
resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0"
@@ -590,20 +575,6 @@ murmurhash@0.0.2:
590575
resolved "https://registry.yarnpkg.com/murmurhash/-/murmurhash-0.0.2.tgz#6f07bd8a1105e709c26fc89420cb5930c24585fe"
591576
integrity sha512-LKlwdZKWzvCQpMszb2HO5leJ7P9T4m5XuDKku8bM0uElrzqK9cn0+iozwQS8jO4SNjrp4w7olalgd8WgsIjhWA==
592577

593-
node-domexception@^1.0.0:
594-
version "1.0.0"
595-
resolved "https://registry.yarnpkg.com/node-domexception/-/node-domexception-1.0.0.tgz#6888db46a1f71c0b76b3f7555016b63fe64766e5"
596-
integrity sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==
597-
598-
node-fetch@^3.2.6:
599-
version "3.2.6"
600-
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-3.2.6.tgz#6d4627181697a9d9674aae0d61548e0d629b31b9"
601-
integrity sha512-LAy/HZnLADOVkVPubaxHDft29booGglPFDr2Hw0J1AercRh01UiVFm++KMDnJeH9sHgNB4hsXPii7Sgym/sTbw==
602-
dependencies:
603-
data-uri-to-buffer "^4.0.0"
604-
fetch-blob "^3.1.4"
605-
formdata-polyfill "^4.0.10"
606-
607578
once@^1.3.0:
608579
version "1.4.0"
609580
resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"
@@ -773,11 +744,6 @@ uuid@^3.3.2:
773744
resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee"
774745
integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==
775746

776-
web-streams-polyfill@^3.0.3:
777-
version "3.2.1"
778-
resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz#71c2718c52b45fd49dbeee88634b3a60ceab42a6"
779-
integrity sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==
780-
781747
wrappy@1:
782748
version "1.0.2"
783749
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"

0 commit comments

Comments
 (0)