Tips for sending a timestamp as input to a stored procedure in TypeScript with the mssql module

Currently, I am utilizing the mssql npm package to communicate with SQL server. I have encountered a dilemma where the variable (which is of type TIMESTAMP in sql server) fetched from a stored procedure is returned as a byte array. Now, I need to pass this variable as a parameter to another stored procedure, which also requires it to be of type TIMESTAMP in sql server. This particular functionality is part of a migration process from dotnet to nodejs.

When retrieving a variable of type DATESTAMP from SQL server, the output appears like this:

invoiceDetail.UpdTS = { type: 'Buffer', data: [ 0, 0, 0, 0, 44, 88, 104, 217 ] }

My goal now is to successfully send this variable into the other stored procedure.

I attempted the following:

.input("UpdTS", sql.####, invoiceDetail.UpdTS) => #### -> undefined

To address this issue, I tried converting the byte array into a hex string and then passing it as follows:

(invoiceDetail.UpdTS was converted to a class, followed by running the data through a function to acquire the hex string)

.input("UpdTS", sql.Varchar, '000000002c5868d9') => error occurred at this point

Answer №1

For this task, you should consider using the sql.Binary or sql.VarBinary input types based on the mssql DataTypes documentation. For example:

const sql = require('mssql')

const sqlConfig = {
    user: process.env.DB_USER,
    password: process.env.DB_PWD,
    database: process.env.DB_NAME,
    server: process.env.DB_SERVER,
    port: parseInt(process.env.DB_PORT ?? '1433'),
    pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
    },
    options: {
        encrypt: false,
        trustServerCertificate: true
    }
}

const foo = async () => {
    try {
        const ID = 1
        const pool = await sql.connect(sqlConfig)
        const result = await pool.request()
            .input('ID', sql.Int, ID)
            .query('select ID, UpdTS from dbo.InvoiceDetail where ID = @ID')
        console.log('Result:')
        console.dir(result)

        const UpdTS_Buffer = result.recordset[0].UpdTS
        console.log('UpdTS_Buffer:')
        console.dir(UpdTS_Buffer)

        await pool.request()
            .input('OldID', sql.Int, ID)
            .input('NewID', sql.Int, ID+1)
            .input('UpdTS', sql.Binary(8), UpdTS_Buffer)
            .execute('dbo.InvoiceDetailUpdate')

    } catch (err) {
        console.error(`An error occurred:`, err)
    }
}
foo().then(() => process.exit(0))

This code block will produce the following output:

Result:
{
  recordsets: [ [ [Object] ] ],
  recordset: [ { ID: 1, UpdTS: [Buffer [Uint8Array]] } ],
  output: {},
  rowsAffected: [ 1 ]
}
UpdTS_Buffer:
Buffer(8) [Uint8Array] [
  0, 0, 0,   0,
  0, 0, 7, 209
]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

having difficulty connecting to an IP address from heroku

Trying to send a ping to an IP address has been successful while testing the application on localhost. getAsync('ping google.com').then(data => { res.send(data); }); When tested on localhost, the result is: Packets: Sent = 4 ...

SPFX - Slow Installation of NPM Packages

Is it necessary to run a npm install for SPFX if all the required modules have already been globally installed? The process of restoring modules can be quite time-consuming, and I am hoping to avoid it if possible. ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

Error: Unable to initiate session: Although some devices were detected, they are not accessible:

Seeking to automate a Web app on iOS Safari for end-to-end testing. Although the following code was successful on an emulator in iOS 17 beta, it appears to not be functioning on a real device (iPhone 12, iOS 16.6). Code snippet for test: const fs = re ...

Encountering: Unable to break down the property 'DynamicServerError' of 'serverHooks' as it does not have a defined value

An error has arisen in a Nextjs app with TypeScript, specifically in the line of my react component which can be found here. This is my inaugural package creation and after several trials, I managed to test it successfully in a similar vite and TypeScript ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

Guide to setting up a new create-react-app project after removing an existing one

(base) Dun-Yan:Web development.HTML ongdunyan$ sudo npm uninstall -g create-react-app Password: up to date, audited 1 package in 429ms found 0 vulnerabilities (base) Dun-Yan:Web development.HTML ongdunyan$ sudo npm install -global <a href="/cdn-cgi/l/ ...

Adding connected types to a list using Typescript

Question regarding Typescript fundamentals. In my code, I have a list that combines two types using the & operator. Here is how it's initialized: let objects: (Object & number)[] = []; I'm unsure how to add values to this list. I attem ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...

The term 'eval' is not identified as an internal or external command, executable program, or batch file in the Windows npm script environment

$ npm run deploy:local > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d5d6d4dcd2d9d3f78799869987">[email protected]</a> deploy:local > eval "`aws-auth-helper ` lerna run deploy:sandbox --stream&quo ...

Having difficulty accessing the PDFKit generated document

I am having trouble generating and opening a PDF file in my NodeJs server. I used PDFKit to create the PDF file, following the code in the documentation: const doc = new PDFDocument({}); doc.text("Test"); const writeStream = fs.createWriteStream("MyTest.p ...

Tips for transferring a null value from a json to a dynamodb

When attempting to pass values one by one to a lambda function and store them in DynamoDB, the first value is saved as null. I have tried the following solutions: Added convertEmptyValues: true var doClient = new AWS.DynamoDB.DocumentClient({convertEmpt ...

I asked for 3 ids to search for nodes/express, but I only received 1 document in return

How can I save only one document from a find query when passing three IDs? https://i.stack.imgur.com/j8UIl.png I intended to retrieve the result from that loop. router.post("/addBand", async (req, res) => { let singers = req.body.singer let sing ...

None of the NPM commands are working due to an error stating: "TypeError: Class extends value undefined is not a constructor

For years, I've had no issues using n to install node. Recently, on my Big Sur mac, I decided to update from v14.17.6 to v16 without any problems. Now when I check the version with node -v, it shows "16.13.1." However, after the update, every npm com ...

How can I efficiently include all css from node_modules in vuejs?

For my Vue.js app built with the webpack template and vuetify, I am starting by importing the vuetify css in my App.vue. <style> @import '../node_modules/vuetify/dist/vuetify.min.css' </style> I'm wondering if this is the c ...

Tips on separating a function into two separate files in Node.js

Hey there! I am just starting to explore Node.js so bear with me if I make any mistakes. So, I have this file: exports.Client = function() { this.example = function(name, callback) { console.log(name); }; ...

Are there type declarations in TypeScript for the InputEvent?

Wondering if there is a @types/* module that offers type definitions for the InputEvent object? For more information about InputEvent, you can visit this link. ...

Tips for retrieving a local variable from inside a callback and using it outside the function

Recently, I started utilizing npm plaid and I'm looking for a way to access the variable trans outside of the plaidClient.getTransactions function. Any suggestions would be greatly appreciated. var trans; var startDate = moment().subtract(30, &apo ...

Learn the best method to turn off caching for specific routes within your Express 4 applications

After attempting various solutions like the ones mentioned in this Stack Overflow thread, Disabling etag Header in Express Node.js, and consulting this GitHub issue, I am still facing issues. My application seems to work fine in Firefox, Opera, and Chrome ...

Can the flow of code in NodeJs be disrupted by throwing an Exception in Javascript?

Is there a way to achieve similar functionality in NodeJS as in Java? I have a code snippet that checks for redundant documents and raises an exception if one is found. However, I want the exception to interrupt the code flow and prevent further execution. ...