Currently I have this typescript/javascript function that connects to my SQL Server and returns data.
async function SQLQuery(query: string, database: string) {
try {
#connects to custom pool manager
const pool = await poolManager.get(database, dbconn[database]);
#Performs query
var result = await pool.request().query(query);
console.log("Result: " + result?.recordset);
return result?.recordset;
} catch (err) {
console.log("Error during SQL query: n" + err);
}
};
When I run a query (ie: Select * from UserTable Where userid=856
), I get the following result:
{"userid":"856",
"username":"username123",
"date":"2022-06-02T13:04:00.88"}
I am able to get the correct value for each query I run, however the result of these queries are always in string. I need them to return as INT (or bigint) and was wondering if this is possible. It would also be nice if I can reformat the date.
When I run the debugger and run the query, the result variable does know what each column type is. For example, id would say BigInt under result.recordset.columns.id.type
Query result in the variable: result
Since I have a big library of queries that are already defined, I can’t change the query itself or manually convert columns to int based off their name. I would need it to return as int after the query is done.
I looked all over this documentation they provide and on the internet but found no luck. https://www.npmjs.com/package/mssql
If someone knows how to resolve this issue it would be great!
Thanks.
Looking through online and finding someone having the same issue.
2
Answers
JavaScript / TypeScript doesn’t have an int type. A JS
Number
is a 64-bit floating point value, so it can represent integers up to 2^53 without loss of precision.JavaScript does have a BigInt type, but it’s relatively new and often doesn’t work with JSON.
For this reason, some interface code will convert BigInts from other platforms or services into strings in JavaScript, to ensure no loss of precision. It looks like Tedious (one of the two drivers used by the mssql package) does this. You may be able to find additional information in the docs and GitHib issues for mssql and whatever driver you’re using on whether there are alternative approaches for handling this.
It’s possibly because of tables data type. Why don’t you use generic type? It may wrap the query result.
For Example