Anyone have experinace with seneca?
I have problem when I try to inclue mesh...
This is hapi route:
server.route({
method: 'GET',
path: '/api/ping',
handler: function (req, reply) {
server.seneca// load the mesh plugin
.use('mesh')
// send a message out into the network
// the network will know where to send format:hex messages
.act('foo:1,v:2', (err: any, out: any) => {
console.log(err)
// prints #FF0000
reply(null, out)
})
}
})
And this is my service:
require('seneca')({
})
//.use('zipkin-tracer', {sampling:1})
.use('entity')
.use('ping-logic')
.ready(function(){
console.log(this.id)
})
logic:
module.exports = function post(options) {
var seneca = this
seneca// provide an action for the format:hex pattern
.add( 'foo:1', function (msg, done) {
done( null, {x:1,v:100+msg.v} )
})
.use('mesh', { auto:true, pin:'foo:1' })
}
I get error
CL MISSING { foo: 1, v: 2 }
Anyone know what is porblem?
I have bumped into this, too. There were two things I had to do:
Use the master branch of seneca-mesh plugin. Unfortunately the published v0.10.0 on NPM is old (2017 March 7), and does not work with seneca v3.4.x
Add seneca.ready(function ()) in your hapi route like this:
server.route({
method: 'GET',
path: '/api/ping',
handler: function (req, reply) {
server.seneca// load the mesh plugin
.use('mesh')
.ready(function () {
// send a message out into the network
// the network will know where to send format:hex messages
this.act('foo:1,v:2', (err: any, out: any) => {
console.log(err)
// prints #FF0000
reply(null, out)
})
})
}
})
Also check this related github issue in which I asked the main contributor if there is a plan to have a new fixed version soon on NPM:
https://github.com/senecajs/seneca-mesh/issues/90
Hope this helps
Related
Devs at my startup have switched login to a magic link system, in which you get inside after clicking a link on the email body.
I have set up a Mailsac email to receive mails containing magic links but I haven't been able to actually follow those links because of the following:
cy.request({
method: "GET",
url: "https://mailsac.com/api/addresses/xxxx#mailsac.com/messages",
headers: {
"Mailsac-Key": "here-goes-the-key",
},
}).then((res) => {
const magicLink = res.body[0].links[0];
cy.origin(magicLink, () => {
cy.visit('/')
});
});
I wasn't able to use cy.visit() either because the magic link URL is slightly different from the baseURL in this testing environment.
So my question is:
How could I follow this cumbersome link to find myself logged in home, or else, is there another way to deal with magic links?
Thanks
The docs say
A URL specifying the secondary origin in which the callback is to be executed. This should at the very least contain a hostname, and may also include the protocol, port number & path. Query params are not supported.
Not sure if this means the cy.visit() argument should not have query params, of just the cy.origin() parameter.
Try passing in the link
cy.request({
...
}).then((res) => {
const magicLink = res.body[0].links[0];
const magicOrigin = new URL(magicLink).origin
cy.origin(magicOrigin, { args: { magicLink } }, ({ magicLink }) => {
cy.visit(magicLink)
});
});
If that doesn't fix it, you could try using cy.request() but you'll have to observe where the token is stored after using the magicLink.
cy.request({
...
}).then((res) => {
const magicLink = res.body[0].links[0];
cy.request(magicLink).then(response =>
const token = response??? // find out where the auth token ends up
cy.setCookie(name, value) // for example
});
});
You need to pass the domain as the first parameter to origin, and do the visit within the callback function, something like this:
const magicLinkDomain = new Url(magicLink).hostname
cy.origin(magicLinkDomain, {args: magicLink}, ({ magicLink }) => {
cy.visit(magicLink);
//...
})
Reference: https://docs.cypress.io/api/commands/origin#Usage
i want to basic authentication using nodejs in documentation. it is written that use "localhost:8080". i am not understanding which url to use. in some other documentation, it is said it deprecated. to make request i am using axios npm package
some things that i tried but didn't work.
- axios.get("https://example.atlassian.net",{data:{username:"",password:""}}).then((result) => {})
please help me guys? i stucked in this problem from last 2 days. Thanks in advance
I think this will help you
Install with the node package manager npm:
$ npm install jira-client
// With ES5
var JiraApi = require('jira-client');
// With ES6
import JiraApi from 'jira-client';
// Initialize
var jira = new JiraApi({
protocol: 'https',
host: 'jira.somehost.com',
username: 'username',
password: 'password',
apiVersion: '2',
strictSSL: true
});
Example: Find the status of an issue
// ES5
// We are using an ES5 Polyfill for Promise support. Please note that if you don't explicitly
// apply a catch exceptions will get swallowed. Read up on ES6 Promises for further details.
jira.findIssue(issueNumber)
.then(function(issue) {
console.log('Status: ' + issue.fields.status.name);
})
.catch(function(err) {
console.error(err);
});
// ES6
jira.findIssue(issueNumber)
.then(issue => {
console.log(`Status: ${issue.fields.status.name}`);
})
.catch(err => {
console.error(err);
});
// ES7
async function logIssueName() {
try {
const issue = await jira.findIssue(issueNumber);
console.log(`Status: ${issue.fields.status.name}`);
} catch (err) {
console.error(err);
}
}
Documentation
documentation here
I'm using Express Graphql server with react native and Relay. My device does connects to the subscription but it does not subscribe to it. Here's my index.js on the server
const subscriptionServer = SubscriptionServer.create(
{
execute,
subscribe,
schema,
onOperation: (message, params, webSocket) => {
console.log(params)
return params;
},
onConnect: () => {
// My device does connects
console.log("client connected")
}
},
{
server,
path: '/subscriptions'
},
);
app.use('/graphql', graphqlHTTP({
schema,
graphiql: true
}));
app.use('/graphiql', graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: `ws://127.0.0.1:8080/subscriptions`
}));
server.listen(PORT, ()=> {
console.log("Groceries running on port " + PORT)
console.log(
`subscriptions is now running on ws://localhost:${PORT}/subscriptions'}`
);
});
The resolver for subscription on the server, it was quite troublesome to figure out since everyone is using executable schema from apolloGraphql.
export default {
type: OrderEdges,
args: {
ShopId: {type: GraphQLID},
},
subscribe: withFilter(() => pubsub.asyncIterator('orderConfirmed'), (payload, variables) => {
console.log(payload)
console.log(variables)
return payload.orderConfirmed.node.ShopId == variables.ShopId;
}),
}
Now the react-native client. My subscription setup with relay environment.
const setupSubscriptions = (config, variables, cacheConfig, observer) => {
const query = config.text; //does console logs the query
const subscriptionClient = new SubscriptionClient(`ws://192.168.0.100:8080/subscriptions`, {reconnect:true});
subscriptionClient.request({query, variables}, (err, result) => {
console.log(err) // doesn't get call inside the request method
observer.onNext(data:result)
})
}
My subscription method,
export default function() {
const variables = {
ShopId: shop.getShop()[0].id
}
requestSubscription(
environment,
{
subscription,
variables,
onCompleted: (res, err) => {
console.log(res)
console.log(err)
},
updater: (store) => {...},
onError: error => console.error(error),
onNext: (response) => {console.log(response)}
});
}
the component where I'm calling to subscribe,
import subscription from '../../GraphQLQueries/subscriptions/orderConfirmed';
class OrdersBox extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
//initializing subscription
orderSubscriptions();
}
When the device starts the app, my device is connected to the web socket as I can see the console.log statement inside the onConnect method in SubscriptionServer. But when the payload is published after a mutation, the subscribe method doesn't get called. I can't seem to figure out what I'm doing wrong. Maybe it's some react-native specific config that I'm missing cuz everything seems to work fine when I test it on graphiql.
I can't find any example of react-native and relay subscriptions used with express graphql.
note: Everything is working when I use subscription with graphiql. But not with react-native and relay.
Thanks in advance guys
....
I wasn't returning the subscriptionClient.request method. Adding a return statement solved the problem. You don't have to return when using subscribe method in subscriptions-transport-ws#0.8.3. But version 0.9.1 replaces the subscribe function with request which does require it to return.
try:
function setupSubscription(config, variables, cacheConfig, observer) {
const query = config.text;
const subscriptionClient = new SubscriptionClient(websocketURL, {
reconnect: true
});
const client = subscriptionClient.request({ query, variables }).subscribe({
next: result => {
observer.onNext({ data: result.data });
},
complete: () => {
observer.onCompleted();
},
error: error => {
observer.onError(error);
}
});
return {
dispose: client.unsubscribe
};
}
subscriptions-transport-ws#0.9.1
I'm really struggling trying to test a request in VueJS using Mocha/Chai-Sinon, with Axios as the request library and having tried a mixture of Moxios and axios-mock-adaptor. The below examples are with the latter.
What I'm trying to do is make a request when the component is created, which is simple enough.
But the tests either complain about the results variable being undefined or an async timout.
Am I doing it right by assigning the variable of the getData() function? Or should Ireturn` the values? Any help would be appreciated.
Component
// Third-party imports
import axios from 'axios'
// Component imports
import VideoCard from './components/VideoCard'
export default {
name: 'app',
components: {
VideoCard
},
data () {
return {
API: '/static/data.json',
results: null
}
},
created () {
this.getData()
},
methods: {
getData: function () {
// I've even tried return instead of assigning to a variable
this.results = axios.get(this.API)
.then(function (response) {
console.log('then()')
return response.data.data
})
.catch(function (error) {
console.log(error)
return error
})
}
}
}
Test
import Vue from 'vue'
import App from 'src/App'
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
let mock = new MockAdapter(axios)
describe('try and load some data from somewhere', () => {
it('should update the results variable with results', (done) => {
console.log('test top')
mock.onGet('/static/data.json').reply(200, {
data: {
data: [
{ id: 1, name: 'Mexican keyboard cat' },
{ id: 2, name: 'Will it blend?' }
]
}
})
const VM = new Vue(App).$mount
setTimeout(() => {
expect(VM.results).to.be.null
done()
}, 1000)
})
})
I am not sure about moxios mock adaptor, but I had a similar struggle. I ended up using axios, and moxios, with the vue-webpack template. My goal was to fake retreiving some blog posts, and assert they were assigned to a this.posts variable.
Your getData() method should return the axios promise like you said you tried - that way, we have some way to tell the test method the promise finished. Otherwise it will just keep going.
Then inside the success callback of getData(), you can assign your data. So it will look like
return axios.get('url').then((response) {
this.results = response
})
Now in your test something like
it('returns the api call', (done) => {
const vm = Vue.extend(VideoCard)
const videoCard = new vm()
videoCard.getData().then(() => {
// expect, assert, whatever
}).then(done, done)
)}
note the use of done(). That is just a guide, you will have to modify it depending on what you are doing exactly. Let me know if you need some more details. I recommend using moxios to mock axios calls.
Here is a good article about testing api calls that helped me.
https://wietse.loves.engineering/testing-promises-with-mocha-90df8b7d2e35#.yzcfju3qv
So massive kudos to xenetics post above, who helped in pointing me in the right direction.
In short, I was trying to access the data incorrectly, when I should have been using the $data property
I also dropped axios-mock-adaptor and went back to using moxios.
I did indeed have to return the promise in my component, like so;
getData: function () {
let self = this
return axios.get(this.API)
.then(function (response) {
self.results = response.data.data
})
.catch(function (error) {
self.results = error
})
}
(Using let self = this got around the axios scope "problem")
Then to test this, all I had to do was stub the request (after doing the moxios.install() and moxios.uninstall for the beforeEach() and afterEach() respectively.
it('should make the request and update the results variable', (done) => {
moxios.stubRequest('./static/data.json', {
status: 200,
responseText: {
data: [
{ id: 1, name: 'Mexican keyboard cat' },
{ id: 2, name: 'Will it blend?' }
]
}
})
const VM = new Vue(App)
expect(VM.$data.results).to.be.null
VM.getData().then(() => {
expect(VM.$data.results).to.be.an('array')
expect(VM.$data.results).to.have.length(2)
}).then(done, done)
})
I have multiple endpoints starting with /networks/{networkId}/*. I don't want to have logic to find a network and execute some extra validation on it, in every handler. Is there any way to solve this on a higher level? Ex. plugins/server method etc?
In every handler I have the following boilerplate code:
import networkRepo from 'common/repositories/network';
// handler.js
export default (req, reply) => {
return networkRepo.findById(req.params.networkId).then(network => {
// Logic to validate whether the logged user belongs to the network
// Logic where I need the network instance
});
}
The best situation would be:
// handler.js
export default (req, reply) => {
console.log(req.network); // This should be the network instance
}
Best way to achieve what you want is to either create a generic function that you can call first inside your handler or alternatively create an internal hapi route which will perform you look-up and return value to your other handler. Internal routes can then be accesses by server.inject from within your other handler, see options called allowInternals for more details, I can write pseudo-code to help!
[{
method: 'GET',
path: '/getNetworkByID/{id}',
config: {
isInternal: true,
handler: function (request, reply) {
return networkRepo.findById(req.params.networkId).then(network => {
// Logic to validate whether the logged user belongs to the network
// Logic where I need the network instance
reply(network.network);
});
}
}
},
{
method: 'GET',
path: '/api/networks/{id}',
config: {
isInternal: true,
handler: function (request, reply) {
request.server.inject({
method: 'GET',
url: '/getNetworkByID/' + request.params.id,
allowInternals: true
}, (res) => {
console.log(res.result.network) //network
});
}
}
}]