Not getting ready event to be triggered. The connected event is triggered multiple times but ready is not. What am I doing wrong? Also connected event should also be triggered only once.
Implementation:
const client = new Cluster(
[
{
host: '127.0.0.1',
port: 7000,
},
],
{
dnsLookup: (address, callback) => callback(null, address),
redisOptions: {
},
},
);
client.on('ready', () => {
log.info('Ready to use Redis');
});
client.on('connect', () => {
log.info('Connected to Redis');
});
client.on('error', (x) => {
log.error(`Disconnected from Redis`);
});
Dockerhub:
redis-cluster:
image: grokzen/redis-cluster
environment:
MASTERS: 1
SLAVES_PER_MASTER: 1
ports:
- "7000:7000"
ioredis version: 4.26.0
Related
I have two microservices with Nest.js both of them connected to RabbitMQ service (one is the publisher and one is the receiver)
From the publisher I am trying to send a message to the receiver and seems that its not doing anything at all
Publisher :
auth.module.ts :
imports:[ClientsModule.registerAsync([
{
name: 'RMQ_SERVICE',
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
transport: Transport.RMQ,
options: {
urls: [`amqp://${configService.get('RMQ_HOST')}:5672`],
queue: 'api-queue',
queueOptions: {
durable: false,
},
},
}),
inject: [ConfigService],
},
]),
]
auth.service.ts :
#Inject('RMQ_SERVICE') private readonly client: ClientProxy,
and using it like that :
this.client.send({ cmd: 'create-user-data' },{});
Receiver :
main.ts :
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.RMQ,
options: {
noAck: false,
urls: [`amqp://${process.env.RMQ_HOST}:5672`],
queue: 'api-queue',
queueOptions: {
durable: false,
},
},
});
await app.startAllMicroservices();
users-data.controler.ts :
#MessagePattern({ cmd: 'create-user-data'})
async createUserData() {
console.log('create-user-data');
}
cant see any errors also i have rabbitmq web monitor and cannot see there any messages
any idea what wrong ?
if ill use emit and EventPattern its working i dont understand why ?
ok so after long digging i just needed to do
const result = await this.client.send(
{ cmd: 'create-user-data' },
{
userId: user.id,
provider,
...socialUser,
},
);
await result.subscribe();
and i received the message on the receiver
I’m having a hard time to mock/test this useLazyQuery case; the hook in the screen:
const [
getSpecificReport,
{ loading: contentLoading, error: contentError, data: content },
] = useLazyQuery<SpecificReportResponse>(
SPECIFIC_REPORT(testResultsData?.getTestResults.testType),
{
client: cmsClient, // <- this is a specific ApolloClient
fetchPolicy: "network-only",
onCompleted: () => {
setScreenData();
},
onError: (err) => {
// (...) omitted for simplification
},
}
);
The mock:
const mocks = [{
request: {
query: SPECIFIC_REPORT('Report Title'),
fetchPolicy: 'network-only',
},
result: {
data: {
allReports: [getReportTestData()],
} as SpecificReportResponse,
},
}]
The test:
...
const { getByText, getAllByText } = render(
<MockedProvider
mocks={mocks}
addTypename={false}
>
<ResultsScreen {...mockProps} />
</MockedProvider>
);
await waitFor(() => {
new Promise((resolve) => setTimeout(resolve, 3000));
expect(getByText(/Something/)).toBeTruthy();
(...)
}
...
What happens is that the screen (ResultsScreen) just acts as if not received the data, i.e. the first expectation fails.
I noticed that if I take off the specific client from the hook, the test works fine - but not the screen, which depends on that.
I wonder if I should pass a “mocked client” to the mocks[0].request or something - I already tried to do it, but no success so far.
Does anyone have any ideas?
Thanks in advance!
I solved it by mocking the client like this (didn't change anything else):
...
const mockCmsClient = new ApolloClient({
link: ApolloLink.from([ApolloLink.empty(), ApolloLink.empty(), ApolloLink.empty()]),
cache: new InMemoryCache(),
});
jest.mock('../../my-module-with-exported-client', () => ({
...jest.requireActual('../../my-module-with-exported-client'),
cmsClient: mockCmsClient,
}));
...
I am trying to verify my deployed contract from truffle and getting "Etherscan has no support for network sepolia with chain id 11155111" error. So I am working with Etherscan and I deployed my contract on sepolia testnet.
How can I solve this problem?
My truffle-config.js
const apikeys = require("./chains/apikeys");
const keys = require("./keys.json");
module.exports = {
plugins: ["truffle-plugin-verify"],
api_keys:{
etherscan: "myApiEtherScan"
},
contracts_build_directory: "./public/contracts",
networks: {
development: {
host: "127.0.0.1",
port: 7545,
network_id: "*",
},
sepolia: {
provider: () =>
new HDWalletProvider(
keys.PRIVATE_KEY,
keys.INFURA_SEPOLIA_URL,
),
network_id: 11155111,
gas:5221975,
gasPrice:20000000000,
confirmations: 3,
timeoutBlocks:200,
skipDryRun: true
}
},
compilers: {
solc: {
version: "0.8.16",
settings: {
optimizer: {
enabled: true, // Default: false
runs: 1000 // Default: 200
}
}
}
},
};
Plugin truffle-plugin-verify doesn't have Sepolia chain support
I added the sepolia api url and etherscan url to constants and it works
const API_URLS = {
...
11155111: 'https://api-sepolia.etherscan.io/api',
...
}
const EXPLORER_URLS = {
...
11155111: 'https://sepolia.etherscan.io/address',
...
}
https://github.com/tafonina/truffle-plugin-verify
I am trying to set up GraphQL Subscriptions but it seems to get connected to the backend but it's not pushing any updates.
On frontend, I am using Nuxt 2 and that's how I am trying to get it working:
That's my test query
export const pendingInquiresSubscription = () => {
return gql`
subscription PendingInquires {
countPendingInquires {
amount
}
}`
}
My smartQuery on the page component
apollo: {
$subscribe: {
pendingInquires: {
query: pendingInquiresSubscription(),
result({ data, loading }) {
this.loading = loading;
console.log(data)
},
error(err) {
this.$notify({ message: `Что-то пошло не так пытаясь обновить количество новый запросов: ${err.message}`, type: 'error' })
},
}
}
},
Backend:
my pubsub
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
const REDIS_DOMAIN_NAME = '127.0.0.1'
const PORT_NUMBER = 6379
const options = {
host: REDIS_DOMAIN_NAME,
port: PORT_NUMBER,
retryStrategy: (times: any) => {
return Math.min(times * 50, 2000);
}
}
export const pubsub = new RedisPubSub({
publisher: new Redis(options),
subscriber: new Redis(options)
})
My Schema:
extend type Subscription {
countPendingInquires: PendingInquires!
}
type PendingInquires {
amount: Int!
}
My resolver
...
Subscription: {
countPendingInquires: {
subscribe: () => pubsub.asyncIterator(['countPendingInquires'])
},
},
...
That's the way I am trying to push the event:
pubsub.publish('countPendingInquires', {
PendingInquires: {
amount: await TelegramInguireModel.find({ }).countDocuments()
}
})
And I also wonder if there is any built-in way to set the initial state for subscriptions.
The issue was in the way I was trying to push the event
The correct way of pushing is like this:
pubsub.publish('countPendingInquires', {
countPendingInquires: { // <- here was the issue
amount: await TelegramInquireModel.find({ }).countDocuments()
}
)
I've just set wrong subscription name
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