How to incorporate SQL Server in a Nuxt.js app

Viewed 1653

I am trying to use SQL Server with a Nuxt app, and incorporate some basic CRUD functionality with tables. Does anybody have any insight or examples on this? I understand (I think) that the calls to the db would be exposed in an api folder and registered as a serverMiddleware. Any examples would be appreciated! I'm currently using the node-mssql package as it seems to be the popular choice.

1 Answers

I would suggest, instead of a proxy library a real ORM library that would allow you to actually create your models and that CRUD operation would then be much easier to maintain rather than write all queries

A common library is Sequelize and you can easily start with something like

in your nuxt.config.js add your serverMiddleware pointing to a brand new folder, for example /api

module.exports = {
  // ...
  serverMiddleware: ['~/api/index.js'],
  env: {
    DB_HOST: process.env.DB_HOST || 'db-host',
    DB_DATABASE: process.env.DB_DATABASE || 'db-database',
    DB_USER: process.env.DB_USER || 'db-user',
    DB_PASS: process.env.DB_PASS || 'db-pass'
  },
  // ...
}

and start creating your express/sequelize calls there just like you are creating a REST API

WIth Sequelize you have a vast number of dialects to choose from, as you want MS SQL, just install tedious package and configure it correctly

const Sequelize = require('sequelize');

const sequelize = new Sequelize(DB_DATABASE, DB_USER, DB_PASS, {
    host: DB_HOST,
    dialect: 'mssql',
    logging: process.env.NODE_ENV !== 'production' ? console.log : false, // eslint-disable-line no-console
    pool: {
        max: 5,
        min: 0,
        idle: 10000,
    },
    define: {
        engine: 'InnoDB',
        collate: 'latin1_swedish_ci',
    },
    dialectOptions: {
        // stream: proxyConnection,
        options: {
            encrypt: true,
            requestTimeout: 300000,
            enableArithAbort: false,
        },
    },
});

After the initial setup, just create your own Models and use them

Sequelize has a really big community ready to help you if you need, either in the docs or through Slack

Related