This is the error:
toJSON` takes 0 argument, 1 provided after:\nr.table(\"users\").get(\"c62b27da-c0c2-4bfd-bd77-aaa95f215ec5\")(\"account\")"
This is my code:
`const userId = hook.params.user.id;
const r = this.options.r;
const accountId = r.table('users').get(userId).getField('account');
if(accountId != null) {
hook.data = Object.assign({}, hook.data, {
createdBy: userId,
account: accountId
});
}`
This is part of the code, but I think it is showing what part of code is giving me error!
Please help!
You're missing a call to .run(conn).
In your code, the constId constant does not contain an id, it contains an unevaluated ReQL query.
See https://rethinkdb.com/docs/introduction-to-reql/
Related
Via CLI, this works: NEAR_ENV=testnet near view dev-1643292007908-55838431863482 nft_tokens_for_owner '{"account_id": "hatchet.testnet"}' and produces the expected result.
I'm now trying to do the same thing via near-api-js but am getting:
Unhandled Runtime Error
Error: Querying [object Object] failed: wasm execution failed with error: FunctionCallError(HostError(GuestPanic { panic_msg: "panicked at 'Failed to deserialize input from JSON.: Error(\"the account ID is invalid\", line: 1, column: 17)', src/contract/nft.rs:65:1" })).
{
"error": "wasm execution failed with error: FunctionCallError(HostError(GuestPanic { panic_msg: \"panicked at 'Failed to deserialize input from JSON.: Error(\\\"the account ID is invalid\\\", line: 1, column: 17)', src/contract/nft.rs:65:1\" }))",
"logs": [],
"block_height": 81208522,
"block_hash": "5vWcrkVjshewYgLZTTHTZgLN7SF3qpYPovnPUUM1ucBt"
}
Call Stack
JsonRpcProvider.query
node_modules/near-api-js/lib/providers/json-rpc-provider.js (123:0)
async Account.viewFunction
node_modules/near-api-js/lib/account.js (366:0)
I've tried multiple totally separate approaches using near-api-js, and they both result in this error.
My current approach is:
export type NFT = Contract & {
nft_mint: (args: any, gas: any, depositAmount: any) => Promise<any>; // TODO Add types
nft_token: (args: any) => Promise<any>;
nft_tokens_for_owner: (args: any) => Promise<any>;
};
export function getNftContract(account: Account) {
const contract = new Contract(
account, // the account object that is connecting
certificateContractName,
{
viewMethods: ['nft_token', 'nft_tokens_for_owner'], // view methods do not change state but usually return a value
changeMethods: ['nft_mint'], // change methods modify state
},
);
return contract;
}
async function getCertificates(accountId: string): Promise<string[]> {
const keyStore = new BrowserLocalStorageKeyStore();
const near = await getNearConnection(keyStore);
const account = new Account(near.connection, ''); // account_id not required for 'view' call
const contract = getNftContract(account);
const response = await (contract as NFT).nft_tokens_for_owner({ account_id: accountId });
console.log({ account, accountId, response });
return []; // TODO
}
I'm using testnet, and the accountId I'm passing is hatchet.testnet.
This was a good lesson for me.
I started looking at the source code of https://docs.rs/near-sdk/3.1.0/src/near_sdk/json_types/account.rs.html#63 and https://docs.rs/near-sdk/3.1.0/src/near_sdk/environment/env.rs.html#816-843
I homed in on that "The account ID is invalid" error message.
But I knew I was passing a valid account ID.
It turns out the problem had nothing to do with NEAR. It was a Next.js / React problem:
My component's account_id was temporarily empty and trying to call nft_tokens_for_owner too soon (i.e. before account_id had been populated with a value).
I had an assignment where I need to have a http POST method which takes int start and int end parameters, then searches database and returns all Cities with population property between the mentioned parameters. Note: I have to use my custom routing for the method.
CitiesController:
[Route("api/cities/search")]
public IHttpActionResult PostSearch(int min, int max)
{
var list = db.Cities
.Where(c => c.Population > min && c.Population < max)
.OrderBy(c => c.Population);
return Ok(list);
}
This is the part in script.js where im calling .ajax POST method.
$("#searchForm").submit(function (e) {
e.preventDefault();
if (token) {
headers.Authorization = "Bearer " + token;
};
var min = $("#searchField1").val();
var max = $("#searchField2").val();
var url = host + "api/cities/search";
var sendData = {
"Min": min,
"Max": max
};
$.ajax({
type: "POST",
url: url,
data: sendData
}).done(fillDataSearch)
.fail(function (data, status) {
alert("!");
});
});
Once i click the submit button in this #searchForm, i get 405 STATUS CODE - Method not allowed Here's what it returns:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult Get(Int32)' in 'Finalni_Kraci.Controllers.CitiesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.</MessageDetail>
</Error>
Based on this, he's targeting GET method with parameter int id (which i do have), but i do not know why.
I tried debugging, everything seems okay until he skips to .fail part of $.ajax. I tried testing this with postman, if i put values in parameteres it works, but if i try to pass values through body
{
"Min": 50000,
"Max": 300000
}
i get 405 Status code again with message: The requested resource does not support http method 'POST'.
I am not really sure what is the correct way to do it. So far i tried what i provided but i am losing idea of what i am doing wrong. Let me know if i need to provide anything else.
This was a silly mistake, i had to use filter object as a parameter for my server's POST method, not two integers.
This is solved.
I am using Graphene-Django and trying to query a mutation.
The client side is like this:
sendMessage = async () => {
const mutation = `mutation sendMessage($text: String!) {
createMessage(text: $text roomSlug: "${this.state.slug}") {
ok
message {
slug
createdDate
text
creator {
firstName
lastName
username
profilePictures {
file
pictureNumber
}
}
}
}
}
`;
const { message, ok } = await apolloClient.mutate(mutation, {text: this.state.text})
.then(result => result.data.createMessage);
The server side is like this:
class CreateMessage(graphene.Mutation):
class Arguments:
text = graphene.String(required=True)
room_slug = graphene.String(required=True)
ok = graphene.Boolean()
message = graphene.Field(MessageType)
def mutate(root, info, text, room_slug):
if info.context.user.is_authenticated is False:
raise PermissionDenied('Login required')
ok = False
room = get_object_or_404(models.Room, slug=room_slug)
message = models.Message(room=room, creator=info.context.user, text=text)
message.save()
ok = True
return CreateMessage(ok=ok, message=message)
I have no idea what things got wrong here. The mutation works when I open a built-in graphql admin view and send it through it. However, it does not work when I send the mutation through the real app and throw this error:
Exception: Received incompatible instance “User Model 1”
So I assumed it should be a client error, but apparently, the error comes from Graphene-Python, which is the server side.
I defintely have both
class MessageType(DjangoObjectType):
class Meta:
model = models.Message
and
class UserType(DjangoObjectType):
class Meta:
model = models.User
UserType is for a creator and MessageType is for a message.
Plus: the UserType works fine in every other queries and mutations. The only place it does not work is this specific mutation.
If anyone runs into this problem, change
message = graphene.Field(MessageType)
to
message = graphene.List(MessageType)
it should work.
Issue Description
I'm trying to update an User when another user click on my Xamarin button.
Then, I used Cloud Code to perform this but it doesnt work
My Code
Here is my complete JS code :
Parse.Cloud.beforeSave("Archive", function(request, response) {
Parse.serverURL = 'https://pg-app-0brffxkawi8lqvf2eyc2isqrs66zsu.scalabl.cloud/1/';
var status = request.object.get("status");
if (status == "validated") {
var event = request.object.get("event");
event.fetch({
success: function(myEvent) {
var coinsEvent = myEvent.get("coins");
var user = request.object.get("user");
user.fetch({
success: function(myUser, coinsEvent, user) {
var email = myUser.get("email");
var coinsUser = myUser.get("coins");
myUser.set("coins", coinsUser + coinsEvent);
return myUser.save(null, {useMasterKey:true});
}
});
}
});
}
response.success();
});
I think myUser.save(null, {useMasterKey:true}); should work
I actually have that error :
Dec 24, 2017, 12:27 GMT+1 - ERRORError generating response for [PUT] /1/classes/_User/1GPcqmn6Hd
"Cannot modify user 1GPcqmn6Hd."
{
"coins": 250
}
Environment Setup
Server
parse-server version : v2.3.3
Server: Sashido
Your success branch never calls response.success() which is a problem... though maybe not THE problem.
You are also doing 2 fetches inside a 'beforeSave' function which is not recommended. 'BeforeSave' must happen very quickly and fetches take time. I would consider thinking through other options.
If you really need to do it this way, consider doing a Parse.Query("event") with an include("user") and trigger the query with query.first({useMasterKey:true}).
Are you sure coinsEvent is what you think it is? Fetch only returns the object fetched... not sure that you can curry in other parameters. I would change your final success routine to (double checking that coinsEvent is valid):
success: function(myUser) {
var coinsUser = myUser.get("coins");
myUser.set("coins", coinsUser + coinsEvent);
return myUser.save(null, {useMasterKey:true}).then(_ => response.success());
}
I'm trying to use highland in combination with the heroku-client. But internally in the heroku client it uses this, even if I try to bind to bind this, the function gives and error message where there is a refrance to this I'm not able to get it to work.
Right no the code looks like this
const Heroku = require('heroku-client');
const hl = require('highland');
var hk = new Heroku({
token: process.env.HEROKU_API_TOKEN
});
var list = hl.wrapCallback(hk.apps().list.bind(hk));
list().toArray((a) => 'console.log(a)')
So this code snippet fails with the following error message:
...node_modules/heroku-client/lib/resourceBuilder.js:35
if (this.params.length !== pathParams.length) {
^
TypeError: Cannot read property 'length' of undefined
Yo! :-)
You're binding to hk and not what hk.apps() return, which is what the list function depends on (it's a member of what hk.apps() returns)
Try this:
const Heroku = require('heroku-client');
const hl = require('highland');
const hk = new Heroku({
token: process.env.HEROKU_API_TOKEN
});
const hkApps = hk.apps();
const list = hl.wrapCallback(hkApps.list.bind(hkApps));
list().toArray((a) => 'console.log(a)')