I have to authenticate to Bitmex API using my Api key but I got this error
Unable to connect: TypeError: Cannot read property 'add' of undefined
'use strict';
var SwaggerClient = require("swagger-client");
var _ = require('lodash');
var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization');
require('dotenv').config();
new SwaggerClient({
// Switch this to `www.bitmex.com` when you're ready to try it out for real.
// Don't forget the `www`!
url: 'https://testnet.bitmex.com/api/explorer/swagger.json',
usePromise: true
})
.then(function(client) {
//console.log(client);
// Comment out if you're not requesting any user data.
client.clientAuthorizations.add("apiKey", new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET));
// Print client capabilities
//
})
.catch(function(e) {
console.error("Unable to connect:", e);
})
Nodejs connector: https://github.com/BitMEX/api-connectors
You're using the latest version of the client, which doesn't do authorizations that way: https://github.com/swagger-api/swagger-js/blob/903569948d5a5c718d7b87d6832a672de4e76afc/docs/MIGRATION_2_X.md#authorizations
new SwaggerClient({
// Switch this to `www.bitmex.com` when you're ready to try it out for real.
// Don't forget the `www`!
url: 'https://testnet.bitmex.com/api/explorer/swagger.json',
usePromise: true,
authorizations: {
apiKey: new BitMEXAPIKeyAuthorization(process.env.BITMEX_API_KEY, process.env.BITMEX_API_SECRET)
}
})
.then(client => {
// Do whatever with client
})
.catch(function(e) {
console.error("Unable to connect:", e);
})
Related
I have an Express + Apollo Server backend. I enabled subscriptions on it using ws and graphql-ws. Everything is working fine.
Now, I would like to handle resolvers errors properly: hide backend details in production, change message based on error type, add a unique ID, etc. On regular mutations, I'm able to do so using the formatResponse function.
On subscriptions, I can't find where I could do it. All I need is a function called before sending data to the client where I have access to data and errors.
How can I do that?
Here's how the WS Server is created:
// Create Web Socket Server
const wsServer = new WebSocketServer({
server: httpServer,
path: '/graphql'
});
const serverCleanup = graphqlWS.useServer(
{
schema: graphqlApp.schema,
context: async (ctx: any) => {
try {
// ...Some auth checking...
return context;
} catch (e) {
throw new ApolloAuthenticationError('you must be logged in');
}
}
},
wsServer
);
And an example of event sending:
import {PubSub} from 'graphql-subscriptions';
// ...
Subscription: {
tree: {
subscribe: withFilter(
() => pubsub.asyncIterator('some_id'),
(payload, variables) => {
const canReturn = true;
//...Some filtering logic...
return canReturn;
}
)
}
},
I am developing an express application which connects to a MongoDB database. It is possible that my express server looses the connection to database, but how should my express server react to this scenario? I prepared the following code where i check for a lost connection and then I kill the app.
const registerCustomer = async (req, res) => {
let validRegistrationCode;
try {
validRegistrationCode = await CustomerRegistrationCode.findOne({ code: req.body.code });
} catch (error) {
if (error instanceof MongoNetworkError || error instanceof MongooseServerSelectionError) {
console.error('Mongo | Mongoose Network Error occurred');
}
process.exit(1);
}
return res.json({ obj: validRegistrationCode });
}
For every access to the DB, I have to check for a connection error and I think this makes the code ugly. How can this be improved?
I think the failure of connection to mongoDB usually doesn't happen or it can also happen in case of network is loss, or your path, syntax is not correct and what you should do is check only once when setup mongoose to connect to your database, every time you save code nodemon will help you check if you have successfully connected
// connect model with database
const mongoose = require('mongoose');
async function connect() {
try {
await mongoose.connect('mongodb://localhost:27017/collections_clothes', {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// useCreateIndex: true,
});
console.log("Access Database Success!");
} catch (error) {
console.log("Access FAIL!");
}
}
module.exports = { connect };
So...I have an api in Next js that uses Prisma Client. Prisma is imported from the global object defined in prisma.ts
Locally everything builds and runs fine. I get no errors and the prisma variable is defined.
However, when it's deployed in Vercel, prisma is undefined...I can't work out why.
If anyone has any suggestions, I'd much appreciate it.
import eBayApi from "#hendt/ebay-api";
import prisma from "../../lib/prisma";
const eBay = new eBayApi({});
export default async (req, res) => {
// Access the provided 'page' and 'limt' query parameters
const code = req.query.code; // this is provided from eBay
console.log(code);
try {
//const token = await eBay.OAuth2.getToken(code);
const token = "bob";
console.log("Prisma handler instance", prisma);
const env_variable = await prisma.variable.upsert({
where: {
variable: "EBAY_TOKEN",
},
update: { value: token },
create: {
variable: "EBAY_TOKEN",
value: token,
},
});
if (env_variable) {
console.log("New Token Stored in DB");
} else console.log("Failed to store new Token");
res.status(200);
res.writeHead(302, {
Location: "/orders",
//add other headers here...
});
res.end();
} catch (e) {
console.error(e);
res.status(400).end();
}
res.writeHead(302, {
Location: "/orders",
//add other headers here...
});
res.end();
};
2021-04-18T19:06:18.680Z 869eb228-423a-4d6a-b05a-f95f5e843c88 ERROR TypeError:
Cannot read property 'upsert' of undefined
at exports.modules.5712.webpack_exports.default (/var/task/nextjs-store/.next/server/pages/api/success.js:55:126)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async apiResolver (/var/task/nextjs-store/node_modules/next/dist/next-server/server/api-utils.js:8:1)
at async Server.handleApiRequest (/var/task/nextjs-store/node_modules/next/dist/next-server/server/next-server.js:67:462)
at async Object.fn (/var/task/nextjs-store/node_modules/next/dist/next-server/server/next-server.js:59:492)
at async Router.execute (/var/task/nextjs-store/node_modules/next/dist/next-server/server/router.js:25:67)
at async Server.run (/var/task/nextjs-store/node_modules/next/dist/next-server/server/next-server.js:69:1042)
at async Server.handleRequest (/var/task/nextjs-store/node_modules/next/dist/next-server/server/next-server.js:34:504)
at async Server. (/var/task/nextjs-store/___next_launcher.js:26:9)
So, I had a play around, and think I found the problem. My prisma table field was a VARCHAR (String), however I was inadvertently trying to store upsert with a JSON object.
Now that I've changed to a JSON field it's working.
So I guess the only problem is that maybe the error wasn't helpul?
Although it was all my stupid fault.
I'm creating a script which is going to automatically receive data from API and store it in MongoDB at specific UTC time.
I use Node-Schedule for scheduling a task at specific time.
CoinMarketCap API for receiving a real time data.
Problem: I receive an undefined in console every second(since the node-schedule is configured to call the code every second). I was looking for any syntax errors or errors in API and wasn't successful. I understand that I receive undefined cause the function doesn't return anything.
Currently doesn't have any ideas what wrong with it at all.
All API keys and DB username password was correct I checked it as well.
Goal: To have the script which is automatically receives data from API and stores it MongoDB collection.
Full Code
const { MongoClient } = require('mongodb');
const schedule = require('node-schedule');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const saveToDatabase = function(BTCdata) {
const url = 'mongodb+srv://name:password#cluster0-1kunr.mongodb.net/<dbname>?retryWrites=true&w=majority';
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, db) => {
if (err) throw err;
const dbo = db.db('Crypto');
const myobj = { Name: 'BTC', Volume: 'BTCdata' };
dbo.collection('Crypto-Values').insertOne(myobj, (error, res) => {
if (error) throw error;
console.log('1 document inserted');
db.close();
});
});
};
function request(method, url) {
return new Promise(((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = resolve;
xhr.onerror = reject;
xhr.send();
}));
}
const j = schedule.scheduleJob('* * * * * *', () => {
request(
'GET',
'http://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=API-KEY-HERE',
)
.then((r1) => {
const x1 = JSON.parse(r1.target.responseText);
const BTCdata = x1.data.find((d) => d.symbol === 'BTC').quote.USD.volume_24h; // creating a variable to store a BTC request from API
console.log(BTCdata);
// Saving to database
saveToDatabase(BTCdata);
})
.catch((err) => {
console.log(err);
});
});
EDIT1:
This is a console log of x1 value.
EDIT2:
Was missing this part -
var request = require('request');
After it was added I start receiving a new error in my console which is :
events.js:287
throw er; // Unhandled 'error' event
^
Error: Invalid URI "GET"
at Request.init
at new Request
at request
at Job.job
at Job.Invoke
at Users/path to node modules/node-schedule
at Timeout.onTimeout
EDIT3:
After correction to the code with #Sureshprajapati answer.
New error appears - TypeError: Cannot read property 'responseText' of undefined
Trying to find solution by myself. Still looking for any advice. Thank you.
var requestPromise = require('request-promise');
requestPromise.get({
uri: 'http://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=API-KEY-HERE',
json: true
}).then(r1 => {
const x1 = JSON.parse(r1.target.responseText);
const BTCdata = x1.data.find(d => d.symbol === 'BTC').quote.USD
.volume_24h; // creating a variable to store a BTC request from API
console.log(BTCdata);
// Saving to database
saveToDatabase(BTCdata);
}).catch(err => {
console.log(err);
});
request supports both streaming and callback interfaces natively. If you'd like request to return a Promise instead, you can use an alternative interface wrapper for request. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use async/await in ES2017.
request-promise (uses Bluebird Promises)
This module is installed via npm:
npm install --save request
npm install --save request-promise
Coming to modifying your code as per documentation:
var requestPromise = require('request-promise');
requestPromise.get({
uri: 'http://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY=API-KEY-HERE',
json: true
}).then(x1 => {
const BTCdata = x1.data.find(d => d.symbol === 'BTC').quote.USD
.volume_24h; // creating a variable to store a BTC request from API
console.log(BTCdata);
// Saving to database
saveToDatabase(BTCdata);
}).catch(err => {
console.log(err);
});
I want to use use tedious in my Azure web app to follow this tutorial https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-nodejs I get the error "Uncaught Error: Module name "tedious" has not been loaded yet" with require('tedious').Connection. How do I load this module in Azure?
The javascript code:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
// Create connection to database
var config = {
userName: '******', // update me
password: '*****', // update me
server: '*******', // update me
options: {
database: 'signals' //update me
}
}
var connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on('connect', function(err) {
if (err) {
console.log(err)
}
else{
queryDatabase()
}
});
function queryDatabase(){
console.log("test");
console.log("test");
console.log('Reading rows from the Table...');
// Read all rows from table
request = new Request(
"SELECT * FROM signals",
function(err, rowCount, rows) {
console.log(rowCount + ' row(s) returned');
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
}
How do I load this module in Azure?
In Azure, you can install Node.js module through Kudu Debug Console which could be accessed via https://<your-web-app-name>.scm.azurewebsites.net/DebugConsole
cd to D:\home\site\wwwroot in the console.
run the following command inside the wwwroot directory: npm install tedious