Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_performance.getEntriesByType is not a function #16

Open
rickhallett opened this issue Jan 21, 2019 · 8 comments
Open

_performance.getEntriesByType is not a function #16

rickhallett opened this issue Jan 21, 2019 · 8 comments

Comments

@rickhallett
Copy link

Thanks for such a great course; I think its one of the best Node courses currently available.

I'm a fan of reading source code unguided and so I have spent some hours going into the FINAL version of the project available in Section 7. The program was bailing out with a silent fatal crash and it took me some time to work out why; in subsequent versions of Node, performance.getEntriesByType was moved to a different css performanceObserverEntryList.getEntriesByType(type) (see v11.x docs).

As this course is still current my suggestion would be to add some Node version checking code that conditionally loads these classes/methods so that other students don't run into the same error. I would be happy to submit a PR with the necessary changes.

@rickhallett
Copy link
Author

@pirple-author Could I get some feedback on this? If this is not a significant problem, I would at least like to know this for my own ongoing development. Thank you!

@rbezerra
Copy link

rbezerra commented Sep 8, 2019

@rickhallett i'm having the same problem, how did you resolved this?

@rickhallett
Copy link
Author

@rbezerra It depends on exactly what you are trying to do with it, but essentially you need to switch to the newer versions of Node's performance API.

I'm pretty disappointed that the author of a premium course didn't take the time to respond to this issue.

@teofiluscandra
Copy link

teofiluscandra commented Feb 9, 2020

@rickhallett @rbezerra Use this code before gather all measurements.

// Log out all the measurements
const measurements = [];
const obs = new PerformanceObserver((list) => {
    measurements.push(...list.getEntries());
});
obs.disconnect();
obs.observe({ entryTypes: ['measure'] });

@akoshevoi
Copy link

Try this before gather all measurements.

// Log out all the measurements
const obs = new PerformanceObserver((list) => {
  const measurement = list.getEntriesByType('measure');

  console.log(
    measurement[0].name, '\x1b[33m\x1b[0m', 
    measurement[0].duration
  );
});
obs.disconnect();
obs.observe({ entryTypes: ['measure'] });

Entire _tokens.post handler looks like

handlers._tokens.post = (data, callback) => {
  _performance.mark('entered function');
  const phone =
    typeof data.payload.phone === 'string' &&
    data.payload.phone.trim().length === 10
      ? data.payload.phone.trim()
      : false;

  const password =
    typeof data.payload.password === 'string' &&
    data.payload.password.trim().length > 0
      ? data.payload.password.trim()
      : false;

  _performance.mark('inputs validated');

  if (phone && password) {
    // Lookup the user who matches that phone number
    _performance.mark('beginning user lookup');
    _data.read('users', phone, (error, userData) => {
      _performance.mark('user lookup complete');
      if (!error && userData) {
        // Hash the sent password, and compare it
        // to the password stored in user object
        _performance.mark('beginning password hashing');
        const hashedPassword = helpers.hash(password);
        _performance.mark('password hashing complete');
        if (hashedPassword === userData.hashedPassword) {
          // If valid, create a new token with a random name.
          // Set expiration date 1 hour in the future.
          _performance.mark('creating data for token');
          const tokenId = helpers.createRandomString(20);
          const expires = Date.now() + 1000 * 60 * 60;
          const tokenObject = {
            phone,
            id: tokenId,
            expires,
          };

          // Store the token
          _performance.mark('beginning storing token');
          _data.create('tokens', tokenId, tokenObject, (error) => {
            _performance.mark('storing token complete');

            // Log out all the measurements
            const obs = new PerformanceObserver((list) => {
              const measurement = list.getEntriesByType('measure');

              console.log(
                measurement[0].name,
                '\x1b[33m\x1b[0m',
                measurement[0].duration
              );
            });
            obs.disconnect();
            obs.observe({ entryTypes: ['measure'] });

            // Gather all the measurements
            _performance.measure(
              'Beginning to end',
              'entered function',
              'storing token complete'
            );

            _performance.measure(
              'Validating user input',
              'entered function',
              'inputs validated'
            );

            _performance.measure(
              'User lookup',
              'beginning user lookup',
              'user lookup complete'
            );

            _performance.measure(
              'Password hashing',
              'beginning password hashing',
              'password hashing complete'
            );

            _performance.measure(
              'Token data creation',
              'creating data for token',
              'beginning storing token'
            );

            _performance.measure(
              'Token storing',
              'beginning storing token',
              'storing token complete'
            );

            if (!error) {
              callback(200, tokenObject);
            } else {
              callback(500, { Error: 'Could not create the new token' });
            }
          });
        } else {
          callback(400, {
            Error:
              "Password did not match the specified user's stored password",
          });
        }
      } else {
        callback(400, { Error: 'Could not find the specified user' });
      }
    });
  } else {
    callback(400, { Error: 'Missing required field(s)' });
  }
};

@Juzzmart
Copy link

Hi,
I have solved this problem by doing the below changes.

Add below dependencies
const { PerformanceObserver } = require('perf_hooks');

And add the below code before "// Gathering all the measurements"

// Log out all the measurements
const obs = new PerformanceObserver((list) => {
const measurement = list.getEntriesByType('measure');
debug('\x1b[33m%s\x1b[0m', measurement[0].name+' '+measurement[0].duration);
});
obs.disconnect();
obs.observe({ entryTypes: ['measure'] });

This solution worked for me :) I hope this works for you too.

@ticomarques
Copy link

ticomarques commented Sep 24, 2021

@Juzzmart great job, your solution is almost 100% complete, because your solution shows just the total duration, while we need to show all measurements with their duration.

Solution:

1 - ADD TO DEPENDENCIES SECTION (ON TOP OF FILE), we need to use an observer to collect the measures, so we need to require it.

const { PerformanceObserver } = require('perf_hooks');

2 - ADD BEFORE // Gather all the measures

// Log out all the measurements const obs = new PerformanceObserver((list) => { const measurements = list.getEntriesByType('measure'); measurements.forEach((measurement)=>{ debug('\x1b[33m%s\x1b[0m',measurement.name+' '+measurement.duration); }); }); obs.disconnect(); obs.observe({ entryTypes: ['measure'] });

3 - REMOVE THE OLD //Log out all the measurements, which is under all _performance.measure(...). It is no longer necessary anymore, because we are using the new one on top of all measurements.

// Log out all the measurements
var measurements = _performance.getEntriesByType('measure');
measurements.forEach(function(measurement){
debug('\x1b[33m%s\x1b[0m',measurement.name+' '+measurement.duration);
});

It is gonna work exactly how it is in the course.

You can check the file here:
https://github.com/ticomarques/api-lean/blob/master/lib/handlers.js

Thank you all !!!!!

@tjcchen
Copy link

tjcchen commented May 21, 2022

PerformanceObserver

Hi @akoshevoi, I think we can make PerformanceObserver instantiated once only. Otherwise we got multiple observers to monitor performance logs when other requests sent in.

Btw, thanks for your answer!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants