NestJS and IPFS - no connection on the server instance - nestjs

I am struggling with binding IPFS node with NestJS instance on the server. All was working fine on the local machine, but on the server, I have a working instance of the IPFS. I know that it works as I can see connected peers and I can see a file uploaded through the server console by https://ipfs.io/ipfs gateway.
The code of the IPFS service is quite simple and it does not produce any errors until I try to upload something.
import { Injectable } from '#nestjs/common';
import { create } from 'ipfs-http-client';
#Injectable()
export class IPFSClientService {
private client = create({
protocol: 'http',
port: 5001
});
public async upload(file: Express.Multer.File): Promise<string> {
const fileToAdd = { path: file.filename, content: file.buffer };
try {
const addedFile = await this.client.add(fileToAdd, { pin: true });
return addedFile.path;
} catch (err) {
console.log('err', err);
}
}
}
Unfortunatelly the error message is enigmatic.
AbortController is not defined
at Client.fetch (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:124:29)
at Client.fetch (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/lib/core.js:141:20)
at Client.post (/home/xxx_secret/node_modules/ipfs-utils/src/http.js:171:17)
at addAll (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add-all.js:22:27)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at Object.last [as default] (/home/xxx_secret/node_modules/it-last/index.js:13:20)
at Object.add (/home/xxx_secret/node_modules/ipfs-http-client/cjs/src/add.js:18:14)
at IPFSClientService.upload (/home/xxx_secret/src/ipfs/ipfs-client.service.ts:20:25)
I will appreciate any help in this matter as I don't have ideas regarding this issue :/

Related

How to resolve socket.io Error "TransportError: xhr poll error"

I want to make a socket.io server using NestJS.
I'm trying communication between server and client on localhost.
however, client(socket.io-client) throw the following error.
TransportError: xhr poll error
the server was running on localhost:3000. and the client was run from node command(node index.js)
server (mock.gateway.ts)
import { SubscribeMessage, WebSocketGateway, MessageBody, ConnectedSocket, WebSocketServer} from '#nestjs/websockets';
import { Socket } from 'socket.io';
#WebSocketGateway()
export class MockGateway {
#WebSocketServer()
server;
#SubscribeMessage('mock')
mock(
#MessageBody() data: string,
#ConnectedSocket() socket: Socket
): void {
console.log(data);
}
}
server (main.ts)
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
client
import { io, Socket } from 'socket.io-client';
const socket = io('ws://localhost:3000', {
path: '/socket.io',
});
socket.emit('mock', 'mock');
I tried set transports to the sockect.io-client. but it makes a timeout error.
import { io, Socket } from 'socket.io-client';
const socket = io('ws://localhost:3000', {
path: '/socket.io',
transports: ['websocket'],
});
socket.emit('mock', 'mock');
Maybe a mistake in module settings. so I use the wscat is debug-tool. It throws the following error, I'm wondering why wscat can connest Nest server.
$ wscat -c ws://localhost:3000/socket.io/\?transport=websocket
Connected (press CTRL+C to quit)
error: Invalid WebSocket frame: RSV1 must be clear
If anyone has any ideas, please comment.

Getting error - connect ECONNREFUSED ::1:80 while for user verification

Getting error - connect ECONNREFUSED ::1:80 while for user verification using #keycloak/keycloak-admin-client
I'm not able to get what is causing this error. Is my baseURL wrong or what?
import { Injectable, Logger } from '#nestjs/common';
import KeycloakAdminClient from '#keycloak/keycloak-admin-client';
#Injectable()
export class ConsoleService {
private readonly logger = new Logger(ConsoleService.name);
async authorizeUser(): Promise<any> {
try {
this.logger.log(` Authorize user started`);
const client = new KeycloakAdminClient( {
baseUrl: 'http://aws.eastus.app.io/realms/login-service/protocol/openid-connect/auth',
realmName: 'login-service'
});
await client.auth({
username: 'test#test.com',
password: 'test',
grantType: 'password',
clientId: 'test'
});
this.logger.log(` Authorize user ended`);
} catch(error) {
console.log(" error ::: ",error.message)
this.logger.log(` Authorize user error: ${error.message}`);
}
}
}
when I use localhost details I'm getting this error: Request failed with status code 404 and base URL I have tried using http://localhost:8080/realms/test/protocol/openid-connect/auth
and http://localhost:8080/auth

OrbitDB can't replicate database on different peer

I have forced with problem in my p2p database orbitdb. Everything works fine while I did not move the database to another server.
const ipfsOptions = {
repo: './ipfs'
}
const ipfs = await IPFS.create(ipfsOptions)
const orbitdb = await OrbitDB.createInstance(ipfs, { directory: './orbitdb' })
try {
publicDB = await orbitdb.open("/orbitdb/zdpuB2kVAbJEk1aZBeeKcwz2ehfDaMWi3upkD3ZHwb15zesLF/hub")
console.log(publicDB.get('hello'))
} catch (err) {
console.log(err)
}
I created an orbit db on another computer and wanted to open from my computer, but it doesn't work, got TimeoutError: request timed out.
TimeoutError: request timed out
at maybeThrowTimeoutError (D:\Source\iprs-node\node_modules\ipfs-core-utils\cjs\src\with-timeout-option.js:35:15)
at D:\Source\iprs-node\node_modules\ipfs-core-utils\cjs\src\with-timeout-option.js:78:9
at runNextTicks (internal/process/task_queues.js:60:5)
at processTimers (internal/timers.js:497:9)
at async Object.read (D:\Source\iprs-node\node_modules\orbit-db-io\index.js:59:17)
at async OrbitDB.open (D:\Source\iprs-node\node_modules\orbit-db\src\OrbitDB.js:452:22)
at async initOrbit (D:\Source\iprs-node\services\orbitdb\index.js:26:20)
at async initAll (D:\Source\iprs-node\index.js:9:5) {
code: 'ERR_TIMEOUT'
}
Does anyone know how to fix it?
Or enlighten me, how this works?

How to get/log/capture the errors from a graphql apollo client query

I am interfacing with a graphql backend using the #apollo/client.
The request i am making returns a 400 bad request and in the network tab i can see the json of the errors.
This is what i would like to log in my code but i am uanble to.
try {
const response = await GraphQLClient.query({
query: GET_PERSON,
variables: {
personId: id,
},
errorPolicy: "all",
});
console.log("response", response);
} catch (err) {
console.log("err", err);
}
When i execute the above it goees into the catch block and i do not have access to the errors object.
err Error: Response not successful: Received status code 400
at new ApolloError (index.ts:54)
at QueryManager.ts:1073
at both (asyncMap.ts:30)
at asyncMap.ts:19
at new Promise ()
at Object.then (asyncMap.ts:19)
at Object.error (asyncMap.ts:31)
at notifySubscription (module.js:137)
at onNotify (module.js:176)
at SubscriptionObserver.error (module.js:229)
at iteration.ts:13
at Array.forEach ()
at iterateObserversSafely (iteration.ts:13)
at Object.error (Concast.ts:185)
at notifySubscription (module.js:137)
at onNotify (module.js:176)
at SubscriptionObserver.error (module.js:229)
at createHttpLink.ts:203
graphqlservice
import { ApolloClient, InMemoryCache } from "#apollo/client";
import { Config } from "./../config";
const FRONTEND_API = `${Config.frontend_api}/graphql` || "";
export const GraphQLClient = new ApolloClient({
uri: FRONTEND_API,
cache: new InMemoryCache(),
}
To get the errors as a json response in the catch method.
console.log(err.networkError.result.errors);
Still very unsure why the response object has an error and errors property and i don't know when these are accessible, maybe someone else could shed some light on that.
export declare type ApolloQueryResult<T> = {
data: T;
errors?: ReadonlyArray<GraphQLError>;
error?: ApolloError;
loading: boolean;
networkStatus: NetworkStatus;
partial?: boolean;
};

Network error: Error: connect ETIMEDOUT 149.154.167.220:443

I have this code block in server.js file:
const Telegram = require('telegram-node-bot')
const tg = new Telegram.Telegram('***********token**************',{
workers:1
});
const pingController = require('./controllers/ping')
,otherwiseController = require('./controllers/otherwise')
tg.router.when(new Telegram.TextCommand('/ping','pingCommand'), new pingController())
.otherwise(new otherwiseController());
and this code block in ping.js file:
const Telegram = require('telegram-node-bot');
class pingController extends Telegram.TelegramBaseController{
pingHandler($){
$.sendMessage('pong');
}
get routes() {
return{
'pingCommand': 'pingHandler'
};
}
}
module.exports = pingController;
and finally this code block in otherwise file:
const Telegram = require('telegram-node-bot');
class otherwiseController extends Telegram.TelegramBaseController{
handler($){
$.sendMessage('Sorry!!!')
}
}
module.exports = otherwiseController;
when I run node server.js, I just got error like this:
[error]
Network error: Error: connect ETIMEDOUT 149.154.167.220:443
at Object._errnoException (util.js:1031:13)
at _exceptionWithHostPort (util.js:1052:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1195:14) request TelegramApiRequest { _method: 'setWebhook', _params: {
url: '' }, _multipart: undefined }
Also, the telegram is filtered in our country!!!, and I use the Siphon 3 proxy.
its because you have't set your proxy for your terminal/cmd
for Linux:
export http_proxy='http://proxyserveraddress:3128'
export https_proxy='https://proxyserveraddress:3128'
for Wndows:
set HTTP_PROXY=http://proxyserveraddress:3128
set HTTPS_PROXY=https://proxyserveraddress:3128
You can use SOCKS5 proxy with the socks5-https-client lib. Example:
const TelegramBot = require('node-telegram-bot-api')
const Agent = require('socks5-https-client/lib/Agent')
const bot = new TelegramBot(process.env.TELEGRAM_API_TOKEN, {
polling: true,
request: {
agentClass: Agent,
agentOptions: {
socksHost: process.env.PROXY_SOCKS5_HOST,
socksPort: parseInt(process.env.PROXY_SOCKS5_PORT),
// If authorization is needed:
// socksUsername: process.env.PROXY_SOCKS5_USERNAME,
// socksPassword: process.env.PROXY_SOCKS5_PASSWORD
}
}
})
This solution to continue developing bot on your local PC (without proxy you can not start bots from Iran and Russia) and it works.

Resources