How to change throughput value of existing azure cosmosdb collection? - rest

I want to reduce the throughput value of existing azure cosmos db collection using this rest API and it's giving a bad/unauthorized error. Kindly help me calling the API with proper input.
https://learn.microsoft.com/en-us/rest/api/cosmos-db/replace-an-offer

You need to provide authorization header
type={typeoftoken}&ver={tokenversion}&sig={hashsignature}

To start from replaceThroughput method
const replaceThroughput = async(req, res, next) => {
let collectionName = _.get(req, 'headers.collectionname');
let offerThroughput = _.get(req, 'headers.offerthroughput');
const container = await cosmosClient.database(process.env.COSMOS_DB_NAME).container(collectionName);
let containerResponse = await container.read().catch((error)=>{
let err = new Error();
err.statusCode = 404;
err.message = 'Collection not found';
next(err);
return;
});
let resourceId = _.get(containerResponse, 'body._rid', '');
console.log(resourceId)
let offerPayload = await getOfferPayload(resourceId);
_.set(offerPayload, 'content.offerThroughput', offerThroughput);
let offerResponse = await replaceOfferThroughput(offerPayload.id, offerPayload);
if (offerResponse.error) {
let err = new Error();
err.statusCode = 500;
err.message = 'Replace resource offer failed';
err.data = offerResponse.error;
next(err);
return;
} else {
res.end(JSON.stringify({'result': 'success', 'message': 'throughput updated', 'data': offerResponse}));
}
next();
};
const getOfferPayload = async (resourceId) => {
var dateString = new Date().toUTCString();
let authString = getAuthorizationTokenUsingMasterKey('GET','offers', '', dateString, process.env.COSMOS_DB_KEY);
const options = {
method: 'GET',
rejectUnauthorized: false,
uri: 'https://' + process.env.COSMOS_DB_NAME + '.documents.azure.com/offers',
headers: {
'x-ms-version': '2018-06-18',
'Authorization': authString,
'x-ms-date': dateString
}
};
try{
let response = await request(options);
response = JSON.parse(response);
response = _.filter(response.Offers, {offerResourceId: resourceId});
return response[0];
}catch(err){
return err;
}
};
const replaceOfferThroughput = async (offerResourceId, offerPayload) => {
var dateString = new Date().toUTCString();
let authString = getAuthorizationTokenUsingMasterKey('PUT','offers', offerResourceId, dateString, process.env.COSMOS_DB_KEY);
const options = {
method: 'PUT',
body: offerPayload,
json: true,
rejectUnauthorized: false,
uri: 'https://' + process.env.COSMOS_DB_NAME + '.documents.azure.com/offers/'+ offerResourceId,
headers: {
'x-ms-version': '2018-06-18',
'Authorization': authString,
'x-ms-date': dateString
}
};
try{
return await request(options);
}catch(err){
return err;
}
};
const getAuthorizationTokenUsingMasterKey = (verb, resourceType, resourceId, date, masterKey) => {
var key = Buffer.from(masterKey, "base64");
var text = (verb || "").toLowerCase() + "\n" +
(resourceType || "").toLowerCase() + "\n" +
(resourceId || "").toLowerCase() + "\n" +
date.toLowerCase() + "\n" +
"" + "\n";
var body = Buffer.from(text, "utf8");
var signature = crypto.createHmac("sha256", key).update(body).digest("base64");
var MasterToken = "master";
var TokenVersion = "1.0";
return encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature);
}
To Create Connection
const CosmosClient = require("#azure/cosmos").CosmosClient;
cosmosClient = new CosmosClient({
endpoint: process.env.COSMOS_DB_URL,
auth: {
masterKey: process.env.COSMOS_DB_KEY
}
});

Related

My server keeps responded with error 404 forbidden. Can anyone see what I am doing wrong here?

My server was working earlier, but now it continuously responds as error 404 and I cannot figure out why. Apparently there is a mistake on my side but I cannot work out what it is.
`var locationLat = '';
var locationLng = '';
var destinationLat = '';
var destinationLng = '';
var quote = 0;
function getQuotes() {
var location = document.getElementById('location').value;
var destination = document.getElementById('destination').value;
fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${location}&key=AIzaSyDpZkgmNpUUE_AfU7-3WM-ExBSH7yb39AI`)
.then(response => response.json())
.then(response => {
locationLat = response.results[0].geometry.location.lat;
locationLng = response.results[0].geometry.location.lng;
}).catch(error => {document.getElementById('quote').innerHTML = "An error has occured" ,console.log(error)})
fetch(`https://ampthilcabs.herokuapp.com/https://maps.googleapis.com/maps/api/geocode/json?address=${destination}&key=AIzaSyDpZkgmNpUUE_AfU7-3WM-ExBSH7yb39AI`, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
})
.then(response => response.json())
.then(response => {
destinationLat = response.results[0].geometry.location.lat;
destinationLng = response.results[0].geometry.location.lng;
}).catch(error => {document.getElementById('quote').innerHTML = "An error has occured" ,console.log(error)})
fetch(`https://ampthilcabs.herokuapp.com/https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=${locationLat},${locationLng}&destinations=${destinationLat},${destinationLng}&key=AIzaSyDpZkgmNpUUE_AfU7-3WM-ExBSH7yb39AI`,
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(response => response.json())
.then(response => {
const miles = parseInt(response.rows[0].elements[0].distance.text);
const price = miles * 2;
document.getElementById('miles').innerHTML = miles
document.getElementById('quote').innerHTML = price;
var value = document.querySelector('#timings').value;
document.getElementById('quoteContainer').style.display = 'flex';
if (document.getElementById('numberOfPeople').value == 5) {
var percentage = price * 0.25;
price = price + percentage;
console.log("Number of people is 5");
document.getElementById('quote').innerHTML = price;
document.getElementById('miles').innerHTML = miles;
}
if (value == 'premium') {
var percentage = price * 0.25;
price = price + percentage;
console.log('Value is premium');
document.getElementById('quote').innerHTML = price;
document.getElementById('miles').innerHTML = miles;
}
var date = new Date(document.getElementById('date').value);
if (date.getDay() == 0) {
var percentage = price * 0.5;
price = price + percentage;
console.log(date.getDay());
document.getElementById('quote').innerHTML = price;
document.getElementById('miles').innerHTML = miles;
}
console.log(date.getDay());
}).catch(error => {document.getElementById('quote').innerHTML = "An error has occured" ,console.log(error)})
}`
Remove server whitelisting
-Changing the server

How to call two actions in same method?

I have 2 actions which are :
This is first
I insert person here :
export const InsertOrUpdate = (person) => {
return (dispatch) => {
var instance = Axios.create({
baseURL: 'url',
// timeout: 1000,
headers: {
"Content-Type": "application/json"
}
});
instance.get("/InsertWorker", {
params: {
Name: person.Name,
Surname: person.Surname,
Duty: person.Duty,
DateOfDay: person.Date.substring(0, person.Date.length - 9),
Shift: person.Shift,
WorkDayCount: person.WorkDayCount,
Equipment: person.Equipment,
Sicil: person.Sicil,
Ship: person.Ship
}
});
}
}
This is second
I call workers here :
export const getSignedWorkers = (collection) => {
return (dispatch) => {
var instance = Axios.create({
baseURL: 'url',
// timeout: 1000,
headers: {
"Content-Type": "application/json"
}
});
instance.get('/GetWorkers', {
params: {
DateOfDay: collection.Tarih,
Shift: collection.Vardiya
}
})
.then((response) => response.data)
.then(x => {
const Signed = str3.filter(x => x.Ship != "" && x.Shift != "H");
console.warn('signed', Signed);
const UnSigned = str3.filter(x => x.Ship == "" || null);
const RemoveOnHolidays = UnSigned.filter(x => x.Shift != "H");
const OnHoliday = str3.filter(x => x.Shift == "H");
const AllWorkers = {};
AllWorkers.signed = Signed;
AllWorkers.Unsigned = RemoveOnHolidays;
AllWorkers.OnHoliday = OnHoliday;
dispatch({ type: FETCH_SIGNED_WORKERS_SIGNED, payload: AllWorkers });
})
.catch((error) => {
console.warn('error', error);
})
}
}
I call this actions here :
_Insert = (person) => {
person.Ship = this.props.gemi_Sefer_No;
this.props.InsertOrUpdate(item); <------- Here I call first action
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var tarih = year + "/" + month + "/" + date;
let collection = {};
collection.Tarih = tarih;
collection.Vardiya = this.props.vardiya == 0 ? "S" : this.props.vardiya == 1 ? "A" : this.props.vardiya == 2 ? "G" : null
this.props.getSignedWorkers(collection); <--- Here I call second action
}
I try to insert workers to database then call all workers from database and use another component with redux. However, sometimes it works correctly sometimes not.
I mean , when I insert to database and call back again, insert worker works right however calling all workers come without worker which I insert last one. As I said, it works sometimes right. What should I do ?. Is that wrong to call two actions in same method ? if it is, what should I do ?

expressjs not allowing variables to retain scope even when they are not local

I want to retain values from a mongoDB document to return them as response. The code goes like:
exports.UserDiseaseInfo = (req, res, next) => {
let retval = {};
let dId = "";
let subDName = "";
let body = req.body;
let UId = (body.UId != undefined) ? body.UId : false;
let SubDId = (body.SubDId != undefined) ? body.SubDId : false;
if (UId == false || SubDId == false) {
res.status(404).send({
response: "Fail",
body: req.body
});
}
subDisease_model.findById(SubDId, function(error, doc) {
dId = doc['DiseaseID'];
subDName = doc['SubDisease'];
});
let data = {
response: 'success',
subDisease: subDName,
DiseaseId: dId
}
res.status(200).send(data);
};
However the output is:
{
"response": "success",
"subDisease": "",
"DiseaseId": ""
}
Whereas it should be
{
"response": "success",
"subDisease": "Migraine",
"DiseaseId": "5ad0850efdcab0ab875c48a4"
}
Any advice what am I missing ?
Because query takes some time to return the data that's why you need to put your data and res.send inside the query callback... That is the only place where doc really has data...
exports.UserDiseaseInfo = (req, res, next) => {
let retval = {};
let dId = "";
let subDName = "";
let body = req.body;
let UId = (body.UId != undefined) ? body.UId : false;
let SubDId = (body.SubDId != undefined) ? body.SubDId : false;
if (UId == false || SubDId == false) {
res.status(404).send({
response: "Fail",
body: req.body
})
}
subDisease_model.findById(SubDId, function(error, doc) {
if (error) {
let data = {
response: 'false',
subDisease: "",
DiseaseId: ""
}
return res.status(404).send(data);
} else {
dId = doc['DiseaseID'];
subDName = doc['SubDisease'];
let data = {
response: 'success',
subDisease: subDName,
DiseaseId: dId
}
return res.status(200).send(data);
}
})
}

Github api get last Users that committed

I want to get the last users exe. last 100 users that committed on github regardless of repo. I've looked around the github api but can't find the specific api call.
You can use Github Events API and filter PushEvent :
https://api.github.com/events?per_page=100
User(s) who have made the last 100 commits on Github
As a PushEvent may have multiple commits, you will have to sum the size for each PushEvent until you reach 100. Note that you also need to exclude PushEvent with 0 commit. You will also have to manage pagination as you can request 100 events max at once (if one request is not enough to get 100 commits).
An example using nodeJS :
var request = require("request");
const maxCommit = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var commitCount = 0;
var page = 1;
var users = [];
while (commitCount < maxCommit) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
commitCount += pushEvents.reduce((it1, it2) => it1 + it2.payload.size, 0);
users = users.concat(pushEvents.map(event => ({
login: event.actor.login,
commitCount: event.payload.size
})));
page++;
}
var count = 0;
for (var i = 0; i < users.length; i++) {
count += users[i].commitCount;
if (count >= maxCommit){
users = users.slice(0, i + 1);
break;
}
}
console.log(users);
}
getEvents();
Last 100 Users who have pushed commits on Github
The only things that changes is that we only check that size field is > 0 and build a map for distinct user.
An example using nodeJS :
var request = require("request");
const maxUser = 100;
const accessToken = 'YOUR_ACCESS_TOKEN';
function doRequest(page){
return new Promise(function (resolve, reject) {
request({
url: 'https://api.github.com/events?per_page=100&page=' + page,
headers: {
'User-Agent': 'Some-App',
'Authorization': 'Token ' + accessToken
}
}, function (err, response, body) {
if (!err) {
resolve(body);
} else {
reject(err);
}
});
})
}
async function getEvents() {
var page = 1;
var users = {};
while (Object.keys(users).length < maxUser) {
var body = await doRequest(page);
var data = JSON.parse(body);
var pushEvents = data.filter(it => it.type == 'PushEvent' && it.payload.size > 0);
for (var i = 0; i < pushEvents.length; i++) {
users[pushEvents[i].actor.login] = pushEvents[i].payload.size;
if (Object.keys(users).length == maxUser) { 
break;
}
}
page++;
}
console.log(users);
}
getEvents();

chrome.serial receiveTimeout Not working.

Below code is a copy with minor edits from https://github.com/GoogleChrome/chrome-app-samples/tree/master/serial/ledtoggle. I am able to send a byte and receive a reply. I am not able to get an TimeoutError event in case of reply is not sent by the client. I have set timeout to 50 ms.
this.receiveTimeout = 50;
Entire code follows.
const DEVICE_PATH = 'COM1';
const serial = chrome.serial;
var ab2str = function(buf) {
var bufView = new Uint8Array(buf);
var encodedString = String.fromCharCode.apply(null, bufView);
return decodeURIComponent(escape(encodedString));
};
var str2ab = function(str) {
var encodedString = unescape((str));
var bytes = new Uint8Array(1);
bytes[0] = parseInt(encodedString);
}
return bytes.buffer;
};
var SerialConnection = function() {
this.connectionId = -1;
this.lineBuffer = "";
this.receiveTimeout =50;
this.boundOnReceive = this.onReceive.bind(this);
this.boundOnReceiveError = this.onReceiveError.bind(this);
this.onConnect = new chrome.Event();
this.onReadLine = new chrome.Event();
this.onError = new chrome.Event();
};
SerialConnection.prototype.onConnectComplete = function(connectionInfo) {
if (!connectionInfo) {
log("Connection failed.");
return;
}
this.connectionId = connectionInfo.connectionId;
chrome.serial.onReceive.addListener(this.boundOnReceive);
chrome.serial.onReceiveError.addListener(this.boundOnReceiveError);
this.onConnect.dispatch();
};
SerialConnection.prototype.onReceive = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.lineBuffer += ab2str(receiveInfo.data);
var index;
while ((index = this.lineBuffer.indexOf('$')) >= 0) {
var line = this.lineBuffer.substr(0, index + 1);
this.onReadLine.dispatch(line);
this.lineBuffer = this.lineBuffer.substr(index + 1);
}
};
SerialConnection.prototype.onReceiveError = function(errorInfo) {
log('Error');
if (errorInfo.connectionId === this.connectionId) {
log('Error');
this.onError.dispatch(errorInfo.error);
log('Error');
}
log('Error');
};
SerialConnection.prototype.connect = function(path) {
serial.connect(path, this.onConnectComplete.bind(this))
};
SerialConnection.prototype.send = function(msg) {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.send(this.connectionId, str2ab(msg), function() {});
};
SerialConnection.prototype.disconnect = function() {
if (this.connectionId < 0) {
throw 'Invalid connection';
}
serial.disconnect(this.connectionId, function() {});
};
var connection = new SerialConnection();
connection.onConnect.addListener(function() {
log('connected to: ' + DEVICE_PATH);
);
connection.onReadLine.addListener(function(line) {
log('read line: ' + line);
});
connection.onError.addListener(function() {
log('Error: ');
});
connection.connect(DEVICE_PATH);
function log(msg) {
var buffer = document.querySelector('#buffer');
buffer.innerHTML += msg + '<br/>';
}
document.querySelector('button').addEventListener('click', function() {
connection.send(2);
});
Maybe I'm reading the code incorrectly, but at no point do you pass receiveTimeout into chrome.serial. The method signature is chrome.serial.connect(string path, ConnectionOptions options, function callback), where options is an optional parameter. You never pass anything into options. Fix that and let us know what happens.