3
\$\begingroup\$

The code is just to check user session.

'use strict';

import Cookie from 'js-cookie';
import  _ from '../helpers';

module.exports = (event) => {
  const spCookieName = 'sp';
  const suCookieName = 'su';
  try {
    const e = event || {};

    let sp = Cookie.get(spCookieName);
    let isNewDevice = 1;
    if (sp) {
      Cookie.set(spCookieName, sp);
      isNewDevice = 0;
    } else {
      sp = _.uuid();
      Cookie.set(spCookieName, sp);
      isNewDevice = 1;
    }

    let su = Cookie.get(suCookieName);
    let isUserNewIn30Days = 0;
    if (!su) {
      Cookie.set(suCookieName, _.uuid(), { expires: 30 });
      isUserNewIn30Days = 1;
    } 

    let pID = Cookie.get('pID'); // page session ID
    if (!pID) {
      pID = _.uuid();
      Cookie.set('pID', pID);
    }

    return {
      uID: sp,
      uNw: isNewDevice,
      uUq: isUserNewIn30Days,
      sID: Cookie.get('sID'),
      pID: pID
    };
  } catch (e) {
    return {};
  }
};
\$\endgroup\$
2
\$\begingroup\$

In some JavaScript engines (if I remember correctly, V8) cannot optimize code inside a try-catch. So while it may be negligible in this case, it's a practice to avoid. The workaround to it is to move out the code from the try catch to a function and call that function from the try-catch instead.

Not all your cookie names appear to be in variables. Move them into variables for consistency as well as to avoid hardcoding the cookie names everywhere.

Lastly, ES6 modules are by default run in strict mode. So no need to define 'use strict';.

The code can be simplified into the following. If you just separate the IO from the data manipulation, you can easily see patterns in the code which you can simplify.

import Cookie from 'js-cookie';
import  _ from '../helpers';

module.exports = (event) => {
  const uidCookieName = 'sp';
  const pidCookieName = 'pID';
  const sidCookieName = 'sID';
  const suCookieName  = 'su';

  const sID = Cookie.get(sidCookieName);
  const uID = Cookie.get(uidCookieName) || _.uuid();
  const pID = Cookie.get(pidCookieName) || _.uuid();
  const su  = Cookie.get(suCookieName)  || _.uuid();

  const uNw = !!Cookie.get(uidCookieName);
  const uUq = su ? 0 : 1; 

  Cookie.set(uidCookieName, uID);
  Cookie.set(pidCookieName, pID);
  Cookie.set(suCookieName, su, { expires: 30 });

  return { uID, sID, pID, uNw, uUq }; 
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.