Tag: dev

  • Knex is a query builder for JavaScript that allows developers to build SQL queries using a fluent and intuitive interface. It supports multiple database systems such as Postgres, MSSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshift. In addition to query building, Knex also provides features for database migrations, making it easy to create and modify database tables using JavaScript code instead of raw SQL scripts. Knex is a powerful tool for managing database operations and simplifying database interactions in JavaScript applications.

    To add Knex to your Node.js project, you can follow these steps.

    Install dependencies:

    yarn add knex

    Make sure to install the driver that corresponds to your database of choice. Knex supports multiple database systems, such as Postgres, MSSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshift. In my case I will use SQLite3.

    yarn add sqlite3

    Init the configuration

    Once you have Knex and the database driver installed, you can start using Knex in your project. You’ll typically need to configure Knex to connect to your database. Create a knexfile.js file in your project’s root directory, and define the necessary configurations based on your environment settings.

    knex init 

    It will create the following knexfile.js

    module.exports = {
    
      development: {
        client: 'sqlite3',
        connection: {
          filename: './dev.sqlite3'
        },
        debug: true
      },
    
      staging: {
        client: 'postgresql',
        connection: {
          database: 'my_db',
          user:     'username',
          password: 'password'
        },
        pool: {
          min: 2,
          max: 10
        },
        migrations: {
          tableName: 'knex_migrations'
        }
      },
    
      production: {
        client: 'postgresql',
        connection: {
          database: 'my_db',
          user:     'username',
          password: 'password'
        },
        pool: {
          min: 2,
          max: 10
        },
        migrations: {
          tableName: 'knex_migrations'
        }
      }
    
    };
    

    Let’s create now our first script with next to run a DB migration

    npx knex migrate:make create_table_users

    As a good practice, create small tasks instead of one task with all the schema. This is useful to detect problems. For example, avoid creating all the init schema in one task, create one task per table and even create another separate task for constraints such as foreign keys

    Use descriptive names such as “create_table_users”. Use also prefix for your actions such as “create_table_…” or “create_column_…”

    Result:

    migrations/20211005153317_create_table_users.js

    Open the file and paste this:

    exports.up = function(knex) {
        return knex.schema.createTable("users", (tb) => {
            tb.increments("id");
            tb.string("username", 100).notNullable();
            tb.string("email", 100).notNullable();
            tb.string("password", 100).notNullable();
        });
    };
    
    exports.down = function(knex) {
        return knex.schema.dropTable("users");
    };
    

    Save it and run:

    knex migrate:latest

    Or select a different environment:

    knex migrate:latest --env production    

    Handy commands:

    npx knex migrate:latest # To run all pending migrations
    npx knex migrate:up # To run the next pending migration
    npx knex migrate:down # To roll back the most recent migration
    npx knex migrate:list # To show current state of migrations.

    Knex is a query builder among other things and it’s an awesome tool to run DB migrations to create tables and modify them as you usually do with SQL scripts.

    That’s it! You have successfully added Knex to your Node.js project. Remember to refer to the Knex documentation for more details on how to use Knex for various database operations.

    You can find more information about Knex on its official website at https://knexjs.org.

  • https://jsonplaceholder.typicode.com

    Example

          
    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => console.log(json))
          
        

    Output

          
    {
      id: 1,
      title: '...',
      body: '...',
      userId: 1
    }
          
        

    Photo by Kai Wenzel on Unsplash

  • About flexsearch package

    flexsearch It’s an awesome package to index in-memory data. You can use it to implement justa. search box in your site or to show related data with the content you are displaying

    How to install it

          
    yarn add flexsearch
          
        

    Or

          
    npm install flexsearch
          
        

    Example

          
    const { Index } = require("flexsearch");
    
    const options = {
        charset: "latin:extra",
        preset: 'match',
        tokenize: 'strict',
        cache: false
    }
    const index = new Index(options);
    
    // my collection
    const recipes = [
        {id:1, title: 'Orange cake'},
        {id:2, title: 'New York-Style Bacon Egg and Cheese Sandwich'},
        {id:3, title: 'Bacon Wrapped Cheese Stuffed Meatloaf'},
        {id:4, title: 'French Yogurt Cake'},
        {id:5, title: 'Gougeres (French Cheese Puffs)'},
        {id:6, title: 'Authentic Brazilian Cheese Bread (Pão de Queijo)'},
        {id:7, title: 'Camarão na Moranga (Brazilian Shrimp Stuffed Pumpkin)'},
        {id:8, title: 'Parmesan Cheese Muffins'},
        {id:9, title: 'Cookie Dough Stuffed Oreos'},
    ]
    
    // index my collection
    recipes.forEach((recipe) =>{
        index.add(recipe.id, recipe.title)
    })
    
    
    // search (it will return an array of ids)
    const ids = index.search('Cookie', 5);
    console.debug(ids);
    // based on the ids returned by the index, look for the recipes for those ids
    const result = recipes.filter((recipe) => ids.includes(recipe.id));
    console.debug(result);
    
    
          
        

    Execution output

          
    [ 9, 1, 4, 6 ]
    [
      { id: 1, title: 'Orange cake' },
      { id: 4, title: 'French Yogurt Cake' },
      { id: 6, title: 'Authentic Brazilian Cheese Bread (Pão de Queijo)' },
      { id: 9, title: 'Cookie Dough Stuffed Oreos' }
    ]
    
          
        

    Photo by Daniel Lerman on Unsplash