How to get the ressources address of a badge - smartcontracts

I'm trying to build an Auction web application based on a scrypto smartcontract.
I have a register function that return a badge, from which I can build proof to call other methods that need authentication.
To build the proof, I need the address of the badge; using the pte-sdk, how would that be possible ?
I use :
const manifestRegistration = new ManifestBuilder()
//call the register function
.callMethod(auction.auctionId, "register", [])
//deposit the resource into my account
.callMethodWithAllResources(accountAddress, "deposit_batch")
.build()
.toString()
const receiptRegistration = await signTransaction(manifestRegistration);
console.log(receiptRegistrationt)
here is receipt :
{
"transactionHash": "b737899a3b78692d2ba49d83ccedeacd66f6168d107a2962828d621d6c73cb37",
"status": "Success",
"outputs": [
"{\"type\":\"Bucket\",\"value\":\"Bucket(1027u32)\"}",
"{\"type\":\"Unit\"}"
],
"logs": [],
"newPackages": [],
"newComponents": [],
"newResources": []
}
How do I know what is the resource in the returned bucket ?
Thank you

The first thing that pops into my head of solving this is returning the address as a string
pub fn register() -> (Bucket, String) -> {
...
(badge, badge.resource_address().to_string())
}
This should pop up in the outputs array

Related

How to use a part of intercepted endpoint as a variable in my stub with Cypress

I am testing a frontend and I want to make my test more efficient
I have the following custom command:
cy.intercept('**/api/classification/dd86ac0a-ca23-413b-986c-535b6aad659c/items/**',
{ fixture: 'ItemsInEditor.json' }).as('ItemsInEditorStub')
This works correctly and is intercepts 25 times :). But the Id in the stub file has to be the same as in the requested Endpoint. Otherwise the frontEnd wilt not process it.
At this point I do not want to make 25 stubfiles in the fixture map.
In the printscreen you can see the different calls I need to intercept. The last ID I would like to save as variable and use it in the stub file
The Stub is like this:
{
"item": {
"version": 3,
"title": "Cars",
"rows": [],
"id": "dynamicIdBasedOnEndPoint" <- *Can we make it dynamic based on the ID in the endpoint*
},
"itemState": "Submitted"
}
UPDATE:
What I have for now is just the basic I guess:
cy.intercept('**/api/classification/*/items/**', {
body:
{
item: {
version: 3,
title: 'Cars',
rows: [],
id: '55eb5a28-24d8-4705-b465-8e1454f73ac8' //Still need this value to be dynamic and always the same as the intercepted '**'(wildcard)
},
itemState: "Submitted"
}
})
.as('ItemsInEditorStub')
cy.fixture('ItemsInEditor.json').then(ModFixture => {
cy.intercept('GET', '**/api/classification/**/items/id/**', (req) => {
const id = req.url.split('/').pop(); // last part of url path
ModFixture.item.id = id; // add the id dynamically
req.reply(ModFixture); // send altered fixture
})
}).as('ItemsInEditorStub')
Thanks to #Fody
You can make a dynamic fixture using javascript.
Ref Providing a stub response with req.reply()
cy.fixture('ItemsInEditor.json').then(fixture => {
cy.intercept('**/api/classification/dd86ac0a-ca23-413b-986c-535b6aad659c/items/**',
(req) => {
const id = req.url.split('/').pop(); // last part of url path
fixture.item.id = id; // add the id dynamically
req.reply(fixture); // send altered fixture
}
).as('ItemsInEditorStub')
})

Does VS Code extensions API support changing cursor position?

I would like to know if the extension API support changing cursor position. I tried to find in the API reference but I couldn't find related function.
The reason behind such function is that
I normally spend much time to move the cursor while writing source code. (by pressing arrow key, home key, pgUp, etc)
So, if I can write an extension that could change cursor location effectively, that could save time a lot. :-)
Thank you in advance!
there is a command named cursorMove which can be run from an extension. In this example the extension uses showInputBox to prompt for the number of lines to move. Then vscode.commands.executeCommand is run to execute the cursorMove command to move down by the entered number of lines:
import * as vscode from 'vscode' ;
let lastNumLines = '1';
// -------------------------- registerCommand_moveCursor --------------------------
export function registerCommand_moveCursor(context: vscode.ExtensionContext)
{
const fullExtensionName = `sample.moveCursorDown`;
let disposable = vscode.commands.registerCommand(fullExtensionName, async ( ) =>
{
const val = await vscode.window.showInputBox(
{ prompt: 'number lines to move', value: lastNumLines });
if (val)
{
lastNumLines = val ;
const numLines = Number(val) ;
await vscode.commands.executeCommand("cursorMove",
{
to: "down", by:'wrappedLine', value:numLines
});
}
});
context.subscriptions.push(disposable);
}
export function activate(context: ExtensionContext)
{
registerCommand_moveCursor(context) ;
}
package.json
"contributes": {
"commands": [
{
"command": "sample.moveCursorDown",
"title": "move cursor down",
"category": "sample"
}
],
}

Internationalization ( i18n ) for express-validator

Is it possible to get messages returned by express-validator into a language other than english for internationalization (i18n) ?
I tried looking into the source code and I could not find it.
express-validator
Thanks
It's probably something you have to create yourself, but it shouldn't be too hard.
When you assign an error message with withMessage() you can send more than just a single string. You can for example send an object. So you can put the error messages, for all the languages, for a particular error, in an object.
Here is an example:
Route:
const countValidation = require('./count.validation');
router
.route('/blogposts')
.get(
countValidation.count,
blogpostController.blogpostsGetAll,
);
Validator (in a separate file called count.validation.js):
const message = {
english: 'count must be between 1 and 1000',
chinese: 'count must be between 1 and 1000, but in chinese',
};
module.exports.count = [
check('count')
.optional()
.isInt({ min: 1, max: 1000 })
.withMessage(message)
];
This response will be sent when validation fails:
{
"errors": {
"count": {
"location": "query",
"param": "count",
"value": "-1",
"msg": {
"english": "count must be between 1 and 1000",
"chinese": "count must be between 1 and 1000, but in chinese"
}
}
}
}
In this particular example the front-end has to choose what error message to display depending on user settings or user agent.
It's also possible to deal with what error message to use on the server side, if we know what language the client is using from the request. We could for example read the accept-language header in the request. Here is an example of how that could be done:
The controller function:
Rather than using this (standard handling of errors, almost straight from the readme):
module.exports.blogpostsGetAll = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.mapped() });
}
// The rest of the function...
};
we use this:
module.exports.blogpostsGetAll = (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const errorsInProperLanguage = handleLanguages(req.headers, errors.mapped());
return res.status(422).json({ errors: errorsInProperLanguage });
}
// The rest of the function...
};
Example function to only use one language:
function handleLanguages(headers, errorsMapped) {
const language = headers['accept-language'].split(',')[0];
for (let errorKey in errorsMapped) {
errorsMapped[errorKey].msg = errorsMapped[errorKey].msg[language];
}
return errorsMapped;
}
Because the accept-language header contains language codes, not language names, we have to modify the message object slightly:
const message = {
'en-US': 'count must be between 1 and 1000',
'zh-CH': 'count must be between 1 and 1000, but in chinese',
};
The message object HAS to contain the first language code in the accept-language header for this to work. The handleLanguage function doesn't handle errors. It's only an example to show how it could be done; don't use it directly.
The error message would change to
{
"errors": {
"count": {
"location": "query",
"param": "count",
"value": "-1",
"msg": "count must be between 1 and 1000, but in chinese"
}
}
}
when the first language in accept-language is zh-CH.
This is now possible with express-validator v5.0.0.
If you pass withMessage() a function, it will be called with the field value, the request, its location and its path.
Example from the docs:
check('something').isInt().withMessage((value, { req, location, path }) => {
return req.translate('validation.message.path', { value, location, path });
}),

API Automation - Is it possible to get response of the post call

I'm learning how to automate API with frisby.js on gmail.api.
I want to create a test where I create and delete(or send) a Draft message.
So I wrote a test which creates a Draft and my question is - can I write a code that gets at least ID of generated response from my Post call?
var frisby = require('frisby');
frisby.create('Create Draft Google')
.post('https://www.googleapis.com/gmail/v1/users/me/drafts?access_token=*my-token-here*', {
message: {
raw: "RGFuJ3MgVG9vbHMgYXJlIGNvb2wh",
id: "1547265285486966899"
}
}, { json: true })
.inspectJSON()
.inspectBody()
.expectStatus(200)
.toss();
So, to clarify, I want to write another part of THIS^ test with
.after(function(err, res, body){}
Steps:
I create a Draft message
I want my test to automatically get ID of just created Draft
So I could Delete it\Send it
Thanks!
When you create a draft, you will get the id of the newly created draft in the response:
Request
POST https://www.googleapis.com/gmail/v1/users/me/drafts?access_token={access_token}
{
"message": {
"raw": "RnJ..."
}
}
Response
{
"id": "r5019331921817638435",
"message": {
"id": "157948187e41b5bb",
"threadId": "157948187e41b5bb",
"labelIds": [
"DRAFT"
]
}
}
Then you can use this id to either send or delete the message.
.afterJSON(function(json){
callback(json.id);
})
I used this function and it worked. Thanks to my friend for help :D
Here're full tests if someone needs it:
This is how I get an ID of created Draft
var frisby = require('frisby');
var new_id = function(frisby, callback)
{
frisby.create('Create Draft Google')
.post('https://www.googleapis.com/gmail/v1/users/me/drafts?access_token=[my_token]', {
message: {
raw: "RGFu...",
}
}, { json: true })
.inspectJSON()
.inspectBody()
.expectStatus(200)
.afterJSON(function(json){
callback(json.id);
})
.toss();
};
module.exports = new_id;
This is how I used it to delete this Draft
var frisby = require('frisby');
var getid_spec = require("./getid_spec.js");
getid_spec(frisby,function(id){
frisby.create('Delete Google Draft Test')
.delete("https://www.googleapis.com/gmail/v1/users/me/drafts/" +id +"?access_token=[my_token]", {})
.expectStatus(204)
.toss();
})

How do I operate the m.withAttr tutorials code?

A contrived example of bi-directional data binding
var user = {
model: function(name) {
this.name = m.prop(name);
},
controller: function() {
return {user: new user.model("John Doe")};
},
view: function(controller) {
m.render("body", [
m("input", {onchange: m.withAttr("value", controller.user.name), value: controller.user.name()})
]);
}
};
https://lhorie.github.io/mithril/mithril.withAttr.html
I tried the above code does not work nothing.
It was the first to try to append the following.
m.mount(document.body, user);
Uncaught SyntaxError: Unexpected token n
Then I tried to append the following.
var users = m.prop([]);
var error = m.prop("");
m.request({method: "GET", url: "/users/index.php"})
.then(users, error);
▼/users/index.php
<?php
echo '[{name: "John"}, {name: "Mary"}]';
Uncaught SyntaxError: Unexpected token n
How do I operate the m.withAttr tutorials code?
Try returning m('body', [...]) from your controller.
view: function (ctrl) {
return m("body", [
...
]);
}
render should not be used inside of Mithril components (render is only used to mount Mithril components on existing DOM nodes).
The example is difficult to operate because it's contrived, it's not meant to be working out-of-the-box. Here's a slightly modified, working version:
http://jsfiddle.net/ciscoheat/8dwenn02/2/
var user = {
model: function(name) {
this.name = m.prop(name);
},
controller: function() {
return {user: new user.model("John Doe")};
},
view: function(controller) {
return [
m("input", {
oninput: m.withAttr("value", controller.user.name),
value: controller.user.name()
}),
m("h1", controller.user.name())
];
}
};
m.mount(document.body, user);
Changes made:
m.mount injects html inside the element specified as first parameter, so rendering a body element in view will make a body inside a body.
Changed the input field event to oninput for instant feedback, and added a h1 to display the model, so you can see it changing when the input field changes.
Using m.request
Another example how to make an ajax request that displays the retrieved data, as per your modifications:
http://jsfiddle.net/ciscoheat/3senfh9c/
var userList = {
controller: function() {
var users = m.prop([]);
var error = m.prop("");
m.request({
method: "GET",
url: "http://jsonplaceholder.typicode.com/users",
}).then(users, error);
return { users: users, error: error };
},
view: function(controller) {
return [
controller.users().map(function(u) {
return m("div", u.name)
}),
controller.error() ? m(".error", {style: "color:red"}, "Error: " + controller.error()) : null
];
}
};
m.mount(document.body, userList);
The Unexpected token n error can happen if the requested url doesn't return valid JSON, so you need to fix the JSON data in /users/index.php to make it work with your own code. There are no quotes around the name field.