Loopback: Passing ctx object in remotemethods - loopbackjs

I am trying to access the ctx object in my remote method.
I have the following code:
MyModel.remoteMethod("getdetails", {
accepts: [
{ arg: "options", type: "object", http: "optionsFromRequest" }
],
http: {
path: "/getdetails",
verb: "get"
},
returns: {
arg: "body",
type: "object",
root: true
}
});
MyModel.getdetails= function( options, cb) {
console.log(options.ctx);
};
I have added { arg: "options", type: "object", http: "optionsFromRequest" } but still I am not getting the ctx in my options. options contain only the accessToken and authorizedRules.
How can get access to ctx in remote methods? I am using loopback3.

Try this:
accepts: [
{arg: 'ctx', type: 'object', http: {source: 'context'}},
...

Related

How to import swagger/?format=openapi to postman from django-rest-swagger without error of format not recognized

Our project use django-rest-swagger to manage API, and we would like to export all api and import Postman, I can get JSON by below url localhost:5000/swagger/?format=openapi, but when I import the file, postman says Error while importing: format not recognized, How to import swagger/?format=openapi to postman from django-rest-swagger without error of format not recognized?
Is there anyone who knows some easy way to solve it? Thanks so much for any advice!!!!!
{
swagger: "2.0",
info: {
title: "TestProjectAPI",
description: "",
version: ""
},
host: "localhost:5000",
schemes: [
"http"
],
paths: {
/api-token/: {
post: {
operationId: "api-token_post",
responses: {
201: {
description: ""
}
},
parameters: [
{
name: "data",
in: "body",
schema: {
type: "object",
properties: {
pic_id: {
description: "",
type: "string"
},
phonenumber: {
description: "",
type: "string"
},
checkcode: {
description: "",
type: "string"
},
user_phone: {
description: "",
type: "string"
},
phone_code: {
description: "",
type: "string"
},
username: {
description: "",
type: "string"
},
password: {
description: "",
type: "string"
}
}
}
}
],
description: "User Login",
summary: "User Login",
consumes: [
"application/json"
],
tags: [
"api-token"
]
}
},
/porject_management/: {
get: {
operationId: "porject_management_list",
responses: {
200: {
description: ""
}
},
parameters: [
{
name: "page",
required: false,
in: "query",
description: "A page number within the paginated result set.",
type: "integer"
},
{
name: "page_size",
required: false,
in: "query",
description: "Number of results to return per page.",
type: "integer"
},
{
name: "search",
required: false,
in: "query",
description: "A search term.",
type: "string"
},
{
name: "project",
required: false,
in: "query",
description: "",
type: "string"
},
{
name: "state",
required: false,
in: "query",
description: "",
type: "number"
},
{
name: "ordering",
required: false,
in: "query",
description: "Which field to use when ordering the results.",
type: "string"
}
],
description: "porject management",
summary: "porject management",
tags: [
"porject_management_post"
]
},
post: {
operationId: "porject_management_post",
responses: {
201: {
description: ""
}
},
parameters: [
{
name: "data",
in: "body",
schema: {
type: "object",
properties: {
project: {
description: "",
type: "string"
},
tc_code: {
description: "",
type: "string"
},
visitors_number: {
description: "",
type: "integer"
},
site_selection: {
description: "",
type: "string"
},
contact_name: {
description: "",
type: "string"
},
contact_number: {
description: "",
type: "string"
},
remark: {
description: "",
type: "string"
},
type: {
description: "",
type: "integer"
},
state: {
description: "",
type: "integer"
},
status: {
description: "",
type: "integer"
},
creater: {
description: "",
type: "string"
},
modifier: {
description: "",
type: "string"
}
}
}
}
],
description: "Porject management",
summary: "Porject management",
consumes: [
"application/json"
],
tags: [
"homemanager"
]
}
},
securityDefinitions: {
basic: {
type: "basic"
}
}
}
Have you tried using:
python3 manage.py generateschema --file openapi-schema.yml
in terminal? Then you can directly import the schema to your POSTMAN. You are providing JSON format, use yaml format for postman it should work.
Finally, I solved my problem by eolink.com,
Firstly, import JSON from localhost:5000/swagger/?format=openapi
Secondly, export Swagger by eolink.com, and then you can import that file to postman!!!

Error Unable to resolve module `http` from web3-providers.umd.js

I installed web3 to link Solidity to React-native. As in the code below, I deployed it from Remix and entered the address and ABI.
import Web3 from "web3";
const web3 = new Web3(
new Web3.providers.HttpProvider("https://127.0.0.1:8545")
);
const address = "0x6cc33e32853a7fb0ac9ac2fb0d54cb56e4fb0f30";
const abi = [
{
constant: false,
inputs: [
{
name: "_MASTER",
type: "address"
},
{
name: "_sitter",
type: "address"
},
{
name: "_sitterprice",
type: "uint256"
}
],
name: "CompleteSharePet",
outputs: [],
payable: true,
stateMutability: "payable",
type: "function"
},
{
constant: false,
inputs: [
{
name: "_OWNER",
type: "address"
},
{
name: "_ownersharetext",
type: "string"
},
{
name: "_ownerprice",
type: "uint256"
}
],
name: "OwnerShareText",
outputs: [
{
name: "",
type: "string"
}
],
payable: false,
stateMutability: "nonpayable",
type: "function"
},
{
constant: false,
inputs: [
{
name: "_ownerseller",
type: "address"
},
{
name: "_petsitter",
type: "address"
},
{
name: "_MASTER",
type: "address"
},
{
name: "_ownerprice",
type: "uint256"
}
],
name: "PetChange",
outputs: [],
payable: true,
stateMutability: "payable",
type: "function"
},
{
constant: false,
inputs: [
{
name: "_PETSITTER",
type: "address"
},
{
name: "_master",
type: "address"
},
{
name: "_ownerprice",
type: "uint256"
}
],
name: "PetChangeTransaction",
outputs: [],
payable: true,
stateMutability: "payable",
type: "function"
},
{
constant: false,
inputs: [
{
name: "_petsittertext",
type: "string"
},
{
name: "_sitterprice",
type: "uint256"
}
],
name: "PetSitterShareText",
outputs: [
{
name: "",
type: "string"
}
],
payable: false,
stateMutability: "nonpayable",
type: "function"
},
{
constant: false,
inputs: [
{
name: "_sitter",
type: "address"
}
],
name: "testsitter",
outputs: [],
payable: true,
stateMutability: "payable",
type: "function"
},
{
constant: false,
inputs: [
{
name: "_master",
type: "address"
},
{
name: "_OWNER",
type: "address"
},
{
name: "_sitterprice",
type: "uint256"
}
],
name: "TransactionSharePet",
outputs: [],
payable: true,
stateMutability: "payable",
type: "function"
},
{
constant: false,
inputs: [
{
name: "hash",
type: "string"
},
{
name: "ipfs",
type: "string"
}
],
name: "uploadImage",
outputs: [],
payable: false,
stateMutability: "nonpayable",
type: "function"
},
{
constant: true,
inputs: [],
name: "AllOwnerCount",
outputs: [
{
name: "",
type: "uint256"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [],
name: "AllPetSitter",
outputs: [
{
name: "",
type: "uint256"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [],
name: "getOwnerAddresses",
outputs: [
{
name: "",
type: "address[]"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [
{
name: "_owner",
type: "address"
}
],
name: "getOwnerInfo",
outputs: [
{
name: "",
type: "string"
},
{
name: "",
type: "string"
},
{
name: "",
type: "string"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [],
name: "getPetSitterAddresses",
outputs: [
{
name: "",
type: "address[]"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [
{
name: "_petsitter",
type: "address"
}
],
name: "getPetSitterInfo",
outputs: [
{
name: "",
type: "string"
},
{
name: "",
type: "string"
},
{
name: "",
type: "string"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [
{
name: "",
type: "uint256"
}
],
name: "OwnerAddresses",
outputs: [
{
name: "",
type: "address"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [
{
name: "",
type: "uint256"
}
],
name: "PetSitterAddresses",
outputs: [
{
name: "",
type: "address"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [
{
name: "_OWNER",
type: "address"
}
],
name: "test",
outputs: [
{
name: "",
type: "uint256"
}
],
payable: false,
stateMutability: "view",
type: "function"
},
{
constant: true,
inputs: [
{
name: "_MASTER",
type: "address"
}
],
name: "test2",
outputs: [
{
name: "",
type: "uint256"
}
],
payable: false,
stateMutability: "view",
type: "function"
}
];
export class WalletSetting extends Component {
test() {
web3.eth.getAccounts().then(console.log);
}
render() {
return this.test;
}
}
export default (myContract = new web3.eth.Contract(abi, address));
The setting was error-free, but the error occurred when import was made to use mycontact
import WalletSetting from "../web3";
.
.
.
</TouchableOpacity>
<WalletSetting />
</LinearGradient>
Error Image
I deleted all the node_modules and all the cache, just like the way in the picture. However, the same error occurred.
I downloaded the web3 version as "^1.0.0-beta.34" to resolve the existing error, but another error occurred.
Error is
Unable to resolve module crypto from /Users/lucky/pettest/node_modules/web3-eth-accounts/src/index.js: Module crypto does not exist in the Haste module map
So I went to Google for reference https://gist.github.com/dougbacelar/29e60920d8fa1982535247563eb63766
And install "node-libs-browser": "^2.2.0", "babelpresetes2015":"^6.24.1",
and create a file called rn-cli.config.js, global.js and import the globaljs file into your web3.js file, but the error was the same.
How can I fix this?
https://gist.github.com/dougbacelar/29e60920d8fa1982535247563eb63766
This linked solution will not solve my problem.
web3 was made to work in a browser environment. The native android environment is different than that of a browser, for example, it doesn't have the crypto class that web3 uses. Using web3 with react native will require some extra configuration. You can follow this guide: https://gist.github.com/dougbacelar/29e60920d8fa1982535247563eb63766.
Also you can find a boilerplate here: https://github.com/dougbacelar/react-native-web3
I have a solution to part of your problem, regarding crypto. Install react-native-crypto and save it as a dependency, then babel-plugin-module-resolver as a dev-dependency, and put a .babelrc file in your project root that contains something like this:
{
"plugins": [
["module-resolver", {
"root": ["."],
"alias": {
"crypto": "react-native-crypto"
}
}]
]
}
This replaces any require('crypto') in your installed packages with require('react-native-crypto'), and it worked for me. In my case however, the same package I had that was missing crypto is also missing http so I came to this thread to hopefully find a polyfill for that too. I am on RN v0.60.3, npm v6.9.0, and node v10.16.0 for anyone interested. Also the package I needed this 'shim' for is the request package, which seems to be a sub-sub-sub-sub-dependency of jest. (npm list request).
I hope this helps somebody!
I found this solution here: https://stackoverflow.com/a/46605706/12375465
and here: https://medium.com/studioarmix/the-joy-of-joi-hacking-node-deps-1337fd5e586f

Loopback js can't read GET request params in the url

I have the following code:
Addresses.getorderHistory = function(address, baseToken, status, length, cb) {
console.log("lenght here -> " + length);
addressService.getorderHistory(address, baseToken, status, length, cb)
.catch(err => cb(err));
};
Addresses.remoteMethod('getorderHistory', {
http: { verb: 'get', path: '/:address/orderHistory' },
accepts: [
{ arg: "address", type: "string", required: true },
{ arg: "base_token", type: "string", required: true, 'http': {source: 'query'} },
{ arg: "status", type: "string", required: true, 'http': {source: 'query'} },
{ arg: "length", type: "string", required: true, 'http': {source: 'query'} }
],
returns: { type: 'object', root: true }
});
When I make a request like this
curl http://localhost:3001/<my root>/addresses/<my address>/orderHistory?base_token=<my token>&status=filled&length=100
It says
Error: status is a required argument
I can basically read address and baseToken values but I can't read status and length. What am I missing?

How to make a web service to send data via url in mongodb via loopback?

In fallowing model I'd like to make a web service to send and save data to database something like.
localhost:3000/api/shops/shopname=cafe del mar&tel=123456&latlng=50.35;56.44&personId=1729451234
shops model
{
"shopname": "string",
"tel": "string",
"latlng": "string",
"address": "string",
"id": "string",
"personId": "string"
}
It's odd to send data via Get request, but if you have considered the security concerns, you may Follow these steps:
Define a remote method:
Shop.remoteMethod('createNewShop',{
accepts: [{arg: 'shopname', type: 'string'},
{arg: 'tel', type: 'string'},
{arg: 'latlng', type: 'string'},
{arg: 'address', type: 'string' },
{ arg: 'id', type: 'string'},
{ arg: 'personId', type: 'string' } ],
returns: {arg: 'result', type: 'string'},
http: {path: '/create-new-shop', verb: 'get'}
});
Implement the createNewShop function in your shop.js file:
var app = require ("../../server/server");
Shop.createNewShop =function(shopname, tel, latlng, address, id, personId, cb){
var instance = {
shopname: shopname,
tel: tel,
latlng: latlng,
address: address,
id: id,
personId: personId
}
var shop = new app.models.Shop(instance)
shop.save().then(function(savedShop,err){
if(err)
throw err
else
cb (null, "done!")
});
}
Now you can call http://localhost:3000/api/shops/create-new-shop?shopname=cafe%20del%20mar&tel=123456&latlng=50.35-56.44&personId=1729451234
Note that semicolon is a reserved char, so you can't use it as a value for your parameter and you should replace it with another char.

Redux Promise Middleware + Redux Mock Store Testing

I tried to test an action creator that returns a promise, using also redux mock store.
import promiseMiddleware from 'redux-promise-middleware';
import nock from 'nock';
import configureStore from 'redux-mock-store';
import { domain, port } from '../../config/environment';
import { GET_ITEMS_START,
GET_ITEMS_SUCCESS } from '../../constants/items';
import { getItems } from './items';
const promise = promiseMiddleware({
promiseTypeSuffixes: ['START', 'SUCCESS', 'ERROR']
});
describe('Get Items', () => {
it('should create GET_ITEMS_SUCCESS action after successfully getting items', (done) => {
nock(`${domain}:${port}`)
.get('/api/items')
.reply(200, {
_id: '1',
text: 'Make Eggs',
completed: false
});
const expectedActions = [
{ type: GET_ITEMS_START },
{ type: GET_ITEMS_SUCCESS, payload: {
data: { _id: '1', text: 'Make Eggs', completed: false }
}}
];
const store = mockStore({}, expectedActions, done);
store.dispatch(getItems());
});
});
and here is my action creator code
export function getItems() {
return {
type: GET_ITEMS,
payload: {
promise: axios.get(`${domain}:${port}/api/items`)
}
};
}
but the result is mismatch because the promise resolved a deep nested objects
Error: Expected { payload: { config: { headers: {}, method: 'get', timeout: 0, transformRequest: [ [Function] ], transformResponse: [ [Function] ], url: 'http://localhost:3000/api/items', withCredentials: undefined }, data: { _id: '1', completed: false, text: 'Make Eggs' }, headers: {}, status: 200, statusText: 'OK' }, type: 'GET_ITEMS_SUCCESS' } to equal { payload: { data: { _id: '1', completed: false, text: 'Make Eggs' } }, type: 'GET_ITEMS_SUCCESS' }
+ expected - actual
{
"payload": {
- "config": {
- "headers": {}
- "method": "get"
- "timeout": 0
- "transformRequest": [
- [Function]
- ]
- "transformResponse": [
- [Function]
- ]
- "url": "http://localhost:3000/api/items"
- "withCredentials": [undefined]
- }
"data": {
"_id": "1"
"completed": false
"text": "Make Eggs"
}
- "headers": {}
- "status": 200
- "statusText": "OK"
}
"type": "GET_ITEMS_SUCCESS"
}
I obviously don't want to copy all of those deep nested properties into my test suite.
Is there a better way of doing this?
If you're writing a unit test, you probably don't need to call the actual REST API. Instead you can mock axios and make it return some fake data which won't be so deep.