newbie question re: nodejs and cryto
var crypto = require('crypto');
var User = {
user1: { name: 'bob', salt: 'randomSalt', password: sha1('mypass', this.salt) }
};
function sha1(pass, salt) {
return crypto.createHmac('sha1', salt).update(pass).digest('hex');
}
Why do I have
console.log(User.user1.password == sha1('mypass', 'randomSalt') //false ?
Answering to myself:
"classic" javascript gotcha :
the context (this) has changed when sha1 is called from the object. Therefore, this.salt is "undefined"
This should work:
var crypto = require("crypto");
function sha1(pass, salt) {
return crypto.createHmac('sha1', salt).update(pass).digest('hex');
}
var User = { name:'Robin', salt:'mysalt'}
User.password = sha1('mypass', User.salt);
// 'cfbc41a870bb7ddd3d7fcc774dd6d2d5850d5340'
Related
I want to collect all transactions for an NFT.
For example, you can display all transactions here:
https://explorer.solana.com/address/2Nzt8TYeAfgJDftKzkb7rgYShVvyXTR7cPVvpqaZ2a4V
or here:
https://solscan.io/token/2Nzt8TYeAfgJDftKzkb7rgYShVvyXTR7cPVvpqaZ2a4V#txs
But is there any way to do this with the API?
I checked
solana-py: https://michaelhly.github.io/solana-py/
and solscan api: https://public-api.solscan.io/docs/
But I could not find a way to do it.
You can use the getSignaturesForAddress RPC method on the mint address and walk backward to get all the transactions.
Here is an example in JS:
import {
Connection,
clusterApiUrl,
ConfirmedSignatureInfo,
PublicKey,
} from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
export const getTxs = async (connection: Connection, pubkey: PublicKey) => {
const txs: ConfirmedSignatureInfo[] = [];
// Walk backward
let lastTransactions = await connection.getConfirmedSignaturesForAddress2(
pubkey
);
let before = lastTransactions[lastTransactions.length - 1].signature;
txs.push(...lastTransactions);
while (true) {
const newTransactions = await connection.getConfirmedSignaturesForAddress2(
pubkey,
{
before,
}
);
if (newTransactions.length === 0) break;
txs.push(...newTransactions);
before = newTransactions[newTransactions.length - 1].signature;
}
return txs;
};
getTxs(
connection,
new PublicKey("2Nzt8TYeAfgJDftKzkb7rgYShVvyXTR7cPVvpqaZ2a4V")
);
The equivalent method in Solana.py is this one https://michaelhly.github.io/solana-py/rpc/api/#solana.rpc.api.Client.get_signatures_for_address
My Flutter Code to fetch posts from API is:
Future<List<Posts>> fetchPosts() async {
var url = 'https://*****.com/wp-json/wp/v2/posts';
final response = await http.get(url, headers: {"Accept": 'application/json'});
if (response.statusCode == 200) {
setState(() {
var jsonData = json.decode(response.body);
for (var p in jsonData) {
Posts post = Posts(
id: p['id'],
date: p['date'],
title: p['title'],
link: p['link'],
postViews: p['views'],
featuredImage: p['featured_image'],
featuredImageBig: p['featured_image_big'],
categories: p['categories'],
comments: p['comments'],
content: p['content'],
);
posts.add(post);
}
});
}
}}
I ask is it best practice code to fetch list of posts ?
thanks advance
Let's assume that you have a Class called Post:
class Post {
final String id;
final String link;
final String imageUrl;
final String title;
Post(this.id, this.link, this.imageUrl, this.title);
factory Post.fromJson(Map<String, dynamic> json) {
return new Post(json['id'], json['link'], json['imageUrl'], json['title']);
}
static Future<List<Post>> get(int skip, int take) async {
var response =
await Api.get('api/v1/posts?SkipCount=$skip&MaxResultCount=$take&');
final responseJson = json.decode(response.body);
final items = (responseJson["items"] as List).map((i) => new Post.fromJson(i));
return items.toList();
}
}
The only other thing you need it the Api class:
import 'dart:async';
import 'package:http/http.dart' as http;
class Api{
static const String BaseUrl = 'http://yourapiwebsite.com/';
static Future<http.Response> get(String url){
return http.get(BaseUrl + url);
}
}
This can handle all of your normal calls. If you are intending to pass dynamic parameters from UI to the API, you can have a bloc and get the parameter from it.
First of all, i think you don't return anything in your function. Also the variable posts, which i guess is a List doesn't exist inside of your function. So I would change it like this:
Future<List<Posts>> fetchPosts() async {
List<Posts> posts = [];
var url = 'https://*****.com/wp-json/wp/v2/posts';
final response = await http.get(url, headers: {"Accept": 'application/json'});
if (response.statusCode == 200) {
setState(() {
var jsonData = json.decode(response.body);
for (var p in jsonData) {
Posts post = Posts(
id: p['id'],
date: p['date'],
title: p['title'],
link: p['link'],
postViews: p['views'],
featuredImage: p['featured_image'],
featuredImageBig: p['featured_image_big'],
categories: p['categories'],
comments: p['comments'],
content: p['content'],
);
posts.add(post);
}
});
}
return posts;
}}
This implementation is good for a small scale application. When the scale of your application increases, and you might support different kind of requests and such kind, you should take a look at the Bloc pattern for best practice.
You can find an example of using the Bloc pattern together with a web API on the channel of Tensor Programming: https://www.youtube.com/watch?v=ALcbTxz3bUw
Here is my code I tried,
var array=[];
var list = this.state.list;
var getList = function(i){
var add = +i + 1;
return {
["value"+add]:{
Description:list[i].Description,
Length:list[i].Length,
Height:list[i].Height,
Weight:list[i].Weight,
VolumeWeight:list[i].VolumeWeight,
ActualWeight:list[i].ActualWeight,
}
}
}.bind(this)
for(var i in list){
array.push(getList(i));
}
var dataArray = array.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
data1 = {
ConsigneeBranchName:this.state.searchText,
ConsigneeBranchCode:this.state.code,
ConsigneeBranchFullAddress:this.state.DAddress,
SenderBranchCode:this.state.code1,
SenderBranchName:this.state.searchTexts,
SenderBranchFullAddress:this.state.Address,
CreatedByEmployeeCode:id,
CreatedByEmployeeFullName:userName,
jsonString:{
JsonValues:{
id:"MyID",
values:dataString
}
}
}
But I want the result is exactly this
var result = {
"ConsigneeBranchName":"",
"ConsigneeBranchCode":"",
"ConsigneeBranchFullAddress":"",
"SenderBranchCode":"",
"SenderBranchName":"",
"SenderBranchFullAddress":"",
"CreatedByEmployeeCode":"",
"CreatedByEmployeeFullName":"",
"jsonString":"{
"JsonValues": {
"id": "MyID",
"values": {
"value1":{
"Description”:"testSmarter1",
"Length”:"60",
"Height”:"50",
"Weight”:"70",
"VolumeWeight”:"75",
"ActualWeight”:”78"
},
"value2:{
"Description":"Documents",
"Length":"120",
"Height":"68",
"Weight":"75",
"VolumeWeight":"122.4",
"ActualWeight":"123"
},
}
}
}
};
Please any one help me
I want the object with dynamic keys within a single object {key1:{des:1,value:as},key2:{des:2,value:aw},key3:{des:3,value:au}}
can you please help me I have tried so many times
see this below image I want this part, inside the single object, I can join multiple objects with dynamic keys
lodash already has a function called keyBy, you can use it to get this functionality. If adding lodash doesn't make sense in your project.
I have implemented a vanilla JS version.
function keyBy(array, mapperFn) {
const resultObj = {};
array.map(item => resultObj[mapperFn(item)] = item);
return resultObj;
}
function arrayToObject (array, keyName = 'id') {
return keyBy(array, function(element) {return element[keyName]});
}
API:
arrayToObject(targetArray, stringNameOfThePorpertyYouWantToUseAsKey);
USAGE:
const listOfUsers = [{name: 'Jenitha', reputation: 6}, {name: 'Chandan', reputation: 3}];
const mapOfUsersByName = arrayToObject(listOfUsers, 'name');
I'm currently creating a library for an API. The endpoints have optional tags, and so I'm trying to create a way to use them in the functions.
import * as request from "request";
class Api {
key: string;
constructor(userInput: string) {
this.key = userInput;
}
champions(tags: object) {
Object.keys(tags).forEach(function(key) {
console.log(key + " = " + tags[key])
})
request(`https://api.champion.gg/v2/champions?api_key=${this.key}&${tags}`, function (error, response, body) {
if(!error && response.statusCode == 200) {
let info = JSON.parse(body)
}
});
}
}
var test = new Api("key")
test.champions({"champData": ["kda", "damage"], "rawr": ["xd", "lmao"]})
So far, the combining of Object.keys and forEach has allowed me to get the response of champData=kda,damage and rawr=xd,lmao, however, I need to be able to assign these to a variable that's usable in the URL. How can I get this to work?
Another issue that may occur later on is that, between each tag, there needs to be an & symbol, but not at the end. I apologize for throwing multiple problems into one, but because this is my first experience with something like this, I'm having many issues.
You can use Object.entries() and URLSearchParams()
const tags = {a:1, b:2, c:3};
const params = new URLSearchParams();
const key = "def";
Object.entries(tags).forEach(([key, prop]) => params.set(key, prop));
const url = `https://api.champion.gg/v2/champions?api_key=${key}&${params.toString()}`;
console.log(url);
Like RTCPeerConnection for example. The api for this is different in firefox, chrome.
This code snippet is just to fix the differences for that api. It demosntrates the annoyance developers face trying to create sites that work in all main modern browsers:...
I am really grateful to whoever created this. It's a great fix.
var RTCPeerConnection = null;
var getUserMedia = null;
var attachMediaStream = null;
var reattachMediaStream = null;
var webrtcDetectedBrowser = null;
function trace(text) {
if (text[text.length - 1] == '\\') {
text = text.substring(0, text.length - 1);
}
console.log((performance.now() / 1000).toFixed(3) + ": " + text);
}
if (navigator.mozGetUserMedia) {
console.log("This appears to be Firefox");
webrtcDetectedBrowser = "firefox";
RTCPeerConnection = mozRTCPeerConnection;
RTCSessionDescription = mozRTCSessionDescription;
RTCIceCandidate = mozRTCIceCandidate;
getUserMedia = navigator.mozGetUserMedia.bind(navigator);
attachMediaStream = function (element, stream) {
console.log("Attaching media stream");
element.mozSrcObject = stream;
element.play();
};
reattachMediaStream = function (to, from) {
console.log("Reattaching media stream");
to.mozSrcObject = from.mozSrcObject;
to.play();
};
MediaStream.prototype.getVideoTracks = function () {
return [];
};
MediaStream.prototype.getAudioTracks = function () {
return [];
};
} else if (navigator.webkitGetUserMedia) {
console.log("This appears to be Chrome");
webrtcDetectedBrowser = "chrome";
RTCPeerConnection = webkitRTCPeerConnection;
getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
attachMediaStream = function (element, stream) {
if (typeof element.srcObject !== 'undefined') {
element.srcObject = stream;
} else
{
if (typeof element.mozSrcObject !== 'undefined') {
element.mozSrcObject = stream;
} else
{
if (typeof element.src !== 'undefined') {
element.src = URL.createObjectURL(stream);
} else {
console.log('Error attaching stream to element.');
}
}
}
};
reattachMediaStream = function (to, from) {
to.src = from.src;
};
if (!webkitMediaStream.prototype.getVideoTracks) {
webkitMediaStream.prototype.getVideoTracks = function () {
return this.videoTracks;
};
webkitMediaStream.prototype.getAudioTracks = function () {
return this.audioTracks;
};
}
if (!webkitRTCPeerConnection.prototype.getLocalStreams) {
webkitRTCPeerConnection.prototype.getLocalStreams = function () {
return this.localStreams;
};
webkitRTCPeerConnection.prototype.getRemoteStreams = function () {
return this.remoteStreams;
};
}
} else {
console.log("Browser does not appear to be WebRTC-capable");
}
Why do the creators of these web browsers have to be so awkward? I cant really understand it lol?
This is summed up in the MDN documentation
This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.
Or the specification:
Publication as an Editor's Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
In short: You are living on the bleeding edge and implementing specifications which are still being designed. Finished specifications tend to get stable, consistent implementations across browsers.
The WebRTC specification has changed a lot in recent years and some browsers still don't support it enough to unprefix their versions of the PeerConnection or getUserMedia APIs (Mozilla recently has).
The snippet you have is from a project called adapter.js. You might want to use that version instead of your outdated one.