Monday, April 29, 2019

Make Your Console Statements Stand Out

Using the Chrome DevTools to debug your JavaScript code is great. Breakpoints are a great way to analyze what is going on with your code. But sometimes you just need an old-fashioned console.log. But if you have an app that is already chatty in development mode with a lot of console messages, there is a way to make your console statement stand out. You may not know that you can format your console statements with CSS. For example:
console.log('%cExample', 'background: #a00; color: #fff; font-weight: bold; font-size: 110%');
will look like this in your console:

Example

A better way to do it, though, is to use a JavaScript template literal. For example:
let xyz = 123;
console.log('%c%s', 'background: #a00; color: #fff; font-weight: bold; font-size: 110%', 
  `The value of xyz is ${xyz}`);
Will produce:

The value of xyz is 123

Now to make it even easier, we can create a VS Code snippet:
"color-console": {
 "prefix": "color-console",
 "body": [
  "console.log('%c%s', 'background: #a00; color: #fff; font-weight: bold; font-size: 110%', `$1`);"
 ],
 "description": "Color coded console message"
},
And then voilĂ 

Tuesday, April 23, 2019

Sequelize Newbie Mistake

Today I inherited a piece of code that looked something like this:
const records = Records.findOne({
    where: {
        pk: 'blah',
    },
    sort: ['dateField', 'DESC']
});
It did not seem to be sorting correctly, so I looked up ordering for Sequelize. Since I am new to Sequelize, I did not know that the correct property is order and not sort. But when I changed it, I got this error message:
Unknown column \'DESC\' in \'order clause\'
It took me longer than I care to admit to see what the issue was. If you pass an array of single items to the order property, it will use them all as part of the sort. So the backend SQL query looked something like this:
SELECT * FROM my_table WHERE pk = 'blah' ORDER BY dateField, DESC
What I really wanted was to pass it an array of arrays to sort on. So the correct code looks like this:
const records = Records.findOne({
    where: {
        pk: myValue,
    },
    order: [
        ['dateField', 'DESC']
    ],
});
Notice that order property now is an array containing an array specifying the field to sort on and the direction with which to sort it.
 
Blogger Templates