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.

Thursday, March 21, 2019

Case-insensitive matching with case-sensitive replacements in JavaScript

That title is a mouth full. Here is what I was trying to accomplish: I had a search term that I wanted to highlight in a body of text. So my code needed to match all occurrences of the search term and then enclose the matched text within some HTML in order to format it. Seems simple enough, but I ran into a couple of issues.

Let's say I am going to format a phone number from a string of digits. I would do it like this:
let phone = '5551234567';
phone = phone.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
But that syntax doesn't work for me here because I need to pass the search pattern as a variable name and I need to specify the "i" and "g" flags. So this code will not work:
const searchTerm = 'xyz';
myText = myText.replace(/searchTerm/ig, 'THE'); // Not valid
First, I use the RegExp constructor to define my pattern.
const searchTerm = 'xyz';
const pattern = RegExp(searchTerm, 'ig');
let myText = 'xyz XYZ xYz';
myText = myText.replace(pattern, 
  `<span class='highlight'>${searchTerm}</span>); 
  // Results will all be lowercase because searchTerm is lowercase
Then I had to create an array of matches that I could then loop through and replace each one individually:
let sampleText = 'This is my sample text: test Test TEST';
const searchText = 'test';
const pattern = new RegExp(searchText, 'ig');
const matches = sampleText.match(pattern, sampleText);
if (matches !== null) {
 matches.forEach((match) => {
  sampleText = sampleText.replace(match, `${match}`);
 });
}
To see this in action, take a look at this JSFiddle.

Thursday, January 31, 2019

Using Workspaces

I'm a big fan of Visual Studio Code's workspaces. In the past, I've used them to separate my work into different projects and applications or different parts of an application (like server-side vs client-side). At the moment we are wrapping up a release at my job so I am often jumping between various tickets. It occurred to me this morning that I could create a new workspace for each ticket. The reason this is helpful is because sometimes I may need these 4 files open for one ticket and a different 5 files open for a different ticket. So instead of keeping them all open and jumping around, I can have just the files I need open for that particular ticket to avoid confusion.

So then the thought occurred to me, what if I could do the same with Chrome? Fortunately, there is an extension for that. Now I can open my application and all my reference material in one workspace and a different set of tabs in another workspace.

Simple. Efficient. I like that.

Tuesday, January 8, 2019

Find This Not That in jQuery

Today at work, I came across a jQuery find statement that was selecting a bunch of different elements but I needed to excluded a single class from the selection. Of course, I hit Google and Stack Overflow for an answer but nothing was quite exactly what I needed. I found the solution and also learned something else about jQuery in the process. So here is what I came up with.

The solution was to chain a filter call to the find statement using the not selector.

Here is a contrived example on CodePen. In this example, I am selecting all buttons except for the btn-danger and btn-warning classes:
var myButtons = $('#main')
     .find('button')
     .filter(':not(".btn-danger,.btn-warning")');

Something I noticed in the console is that there is an object created called prevObject. This object contains the matched elements before the filter is applied which could be useful.

Thursday, June 7, 2018

Using the VS Code Integrated Terminal with Remote Hosts

I am in the process of writing some server-side scripts on a remote server. There are three things that would make it easier:

1. If I could write the code directly to the server from VS Code
2. If the integrated terminal in VS Code would automatically log me into that server
3. If I could easily toggle between the code window and the terminal window

I am going to describe how to do all of those things.

Writing Code Directly to the Server in VS Code

To write code directly to the server, I am using an SFTP extension I found in the VS Code Marketplace. The extension I am using is simply called sftp.

To configure it, you open the command palette (Cmd+Shift+P) and select SFTP: Config. This will generate a file called sftp.json within the .vscode directory of your workspace. You can check out the full config options, but basically you just need to specify the host, username, and remote path. So that my code is automatically saved to the server, I set the uploadOnSave option to true in the sftp.json file.

And so that I don't have to log in every time, I am using the privateKeyPath option as well. I won't go into the details here of how to set up SSH for auto login without a password but it is definitely a time saver.


Automatically Logging into the Remote Server

The next thing I wanted to accomplish was automatically logging into the remote server in the integrated terminal. To do that I need to update my workspace settings.

To start I select Code ▶ Preferences ▶ Settings to open the Workspace Settings. Then within the settings, I add some JSON to tell it to call the ssh command with an argument of the server name.


Also, because I like to color code my terminal windows, I found the workbench.colorCustomizations setting which allows me to set a value for terminal.background.

For this change to take effect, I have to restart VS Code. A security feature prompts me to make sure this is what I really want to do. This only happens the first time.


I have to restart VS Code one more time. This time when I open the terminal, it automatically logs me into the remote server so that I can test my scripts.

Toggling Between the Code Window and the Terminal Window

While I like having the terminal window integrated into my IDE, I don't like having to use the mouse to click back and forth between the two windows. Fortunately, someone on Stack Overflow had already solved that problem.

This time I go to Code ▶ Preferences ▶ Keyboard Shortcuts. To make the change, I first have to click on the keybindings.json link:


Then I can paste in the code for my settings.


Now after I save my code, I simply press Ctrl+` to switch to the terminal window, test my code, and then press Ctrl+` again to return back to my code.

Tuesday, May 22, 2018

Changing Chrome Policies for Testing

I recently ran into a situation where I was pretty sure that a group policy was breaking functionality on my intranet app, but I needed a way to test that theory. After some research, I finally figured out a way to do this.

I am working on an Oracle Virtual Box VM of Windows 7. Because it's a VM on my laptop, I have complete control over the operating system. To set the policy, I used the Windows Registry Editor regedit.

Within Computer\HKEY_CURRENT_USER\Software\Policies, I created a new key called Google. Then within Google, I created a new key called Chrome.

From there, I just needed to add policies one by one until I figured out which one was breaking my app. The link at https://www.chromium.org/administrators/policy-list-3 provides a full list of policies. After saving a policy, I would restart Chrome and the new policy would be enabled. Sure enough, I found the culprit. By toggling this policy and restarting Chrome I could verify that the application worked and then broke with each change of the policy.

Example of Chrome policy set in Windows registry

Tuesday, April 24, 2018

Stopping a page redirect to look at JavaScript console

I am currently assisting another developer troubleshoot an issue he's having. In the code, there is a JavaScript function call tied to the onclick event of the HTML link. Because the JavaScript code is failing, the page is redirecting before I have a change to look at the console log to see what the error is. One solution is to use a breakpoint in the code and that's what I'll ultimately do. But I found this great hack.

window.addEventListener("beforeunload", function() { debugger; }, false)

By running this code in the console first, it will pause execution and allow me to see the error in the console.
 
Blogger Templates