SvelteKit - can I consume a +server.ts endpoint from a store? - frontend

In my svelte website, I want to consume an endpoint inside a store, to fetch a list of servers for me to display in html divs. I cannot seem to understand how to call the API for me to fetch the servers.
from the serverSection component
(https://github.com/maxijabase/electricservers.com.ar/blob/master/src/components/serverSection.svelte)
src/components/serverSection.svelte
<script lang="ts">
export let bgImage: string
export let logo: string
export let text: string
import { fetchServers, serversStore } from '../stores/servers'
import Server from './server.svelte'
fetchServers()
</script>
<!-- some html -->
I'm trying to fetch a list of servers from an endpoint I created in a +server.ts file
(https://github.com/maxijabase/electricservers.com.ar/blob/master/src/routes/api/%2Bserver.ts)
this is src/stores/servers.ts
import { writable, type Writable } from 'svelte/store'
export const serversStore: Writable<any> = writable()
export const fetchServers = async () => {
const response = await fetch('/api', {
method: 'GET',
headers: {
'content-type': 'application/json',
accept: 'application/json',
},
})
serversStore.set(response)
}
this is src/routes/api/+server.ts
import type { RequestHandler } from './$types'
import { Server } from '#fabricio-191/valve-server-query'
import { serverList } from 'src/servers/serversList'
import { json } from '#sveltejs/kit'
export const GET: RequestHandler = async () => {
let infoList: Server.Info[] = []
for await (const server of serverList) {
const sv = await Server({ ip: server.ip, port: server.port, timeout: 3000 })
const svInfo = await sv.getInfo()
infoList.push(svInfo)
}
return json(infoList)
}
but I'm getting
Cannot read properties of undefined (reading 'length')
TypeError: Cannot read properties of undefined (reading 'length')
at Module.each (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1841:31)
at eval (/src/components/serverSection.svelte:28:63)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
at eval (/src/routes/+page.svelte:20:120)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
at Object.default (root.svelte:41:38)
at eval (/src/routes/+layout.svelte:11:41)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
at root.svelte:40:37
at $$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1876:22)
C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\index.js:105
Error.captureStackTrace(err, this)
^
TypeError: Failed to parse URL from /api
at fetch (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\index.js:105:13)
at async Module.fetchServers (/src/stores/servers.ts:8:20) {
[cause]: TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:372:5)
at URL.onParseError (node:internal/url:553:9)
at new URL (node:internal/url:629:5)
at new Request (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\lib\fetch\request.js:78:21)
at fetch (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\lib\fetch\index.js:136:21)
at fetch (C:\Users\Maxi\Documents\Programming\electricservers.com.ar\node_modules\.pnpm\undici#5.14.0\node_modules\undici\index.js:103:20)
at Module.fetchServers (/src/stores/servers.ts:8:26)
at eval (/src/components/serverSection.svelte:19:24)
at Object.$$render (/node_modules/.pnpm/svelte#3.55.0/node_modules/svelte/internal/index.mjs:1878:22)
at eval (/src/routes/+page.svelte:20:120) {
input: '/api',
code: 'ERR_INVALID_URL'
}
}
 ELIFECYCLE  Command failed with exit code 1.
I have no idea how to do this properly

Related

I can't create the pact-file, because the Query Path isn't correct

When I run the consumer part, Its get the following error:
1 failing
1) The Project API
"after each" hook for "returns the correct response":
Error: Pact verification failed - expected interactions did not match actual.
at new VerificationError (node_modules\#pact-foundation\pact\errors\verificationError.js:19:42)
at C:\Nexus\NovoTesteContrato\node_modules\#pact-foundation\pact\httpPact.js:102:23
at processTicksAndRejections (internal/process/task_queues.js:95:5)
And
Pact verification failed!
Actual interactions do not match expected interactions for mock MockService.
Missing requests:
GET /Project?Responsible=teste.k6%40k6.com&Name=Teste+para+a+pequisa
See C:/Nexus/NovoTesteContrato/logs/mockserver-integration.log for details.
My mock API and official API don't aceppt:
GET /Project?Responsible=teste.k6%40k6.com&Name=Teste+para+a+pequisa
My mock API and official API aceppt:
GET /Project?responsible=teste.k6%40k6.com&Name=Teste%20para%20a%20pequisa
How do I make PACT-JS send the request with "Test%20for%20a%20research" and not with "Test+for+the+research"?
My code is
import 'dotenv/config';
import { Matchers, Pact } from '#pact-foundation/pact';
import { eachLike, somethingLike, integer } from '#pact-foundation/pact/src/dsl/matchers';
import path from 'path';
import { GetProjectScenario1 } from '../../../api';
const mockProvider = new Pact({
consumer: 'TestProjectApi',
provider: 'Nexus',
log: path.resolve(process.cwd(), "__tests__/contract/logs", "pact.log"),
dir: path.resolve(process.cwd(), "__tests__/contract/pacts"),
logLevel: 'INFO',
pactfileWriteMode: 'overwrite',
spec: 2,
cors: true
});
let ProjectJsonSucessfull = ""
let responsibleSceario1 = "teste.k6#k6.com"
describe('Given - API TEST Nexus Project STAY ONLINE', () => {
beforeAll(async () => {
ProjectJsonSucessfull = require("./resources/tmp/Get_project_successfull_response.json")
})
describe('When I Search Project with sucessfull', () => {
beforeAll(async () =>
await mockProvider.setup().then(() => {
mockProvider.addInteraction({
uponReceiving: 'Only responsible',
withRequest: {
method: 'GET',
path: `/Project?Responsible=${responsibleSceario1}`
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json',
},
body: Matchers.like(ProjectJsonSucessfull).contents
}
});
})
);
afterEach(() => mockProvider.verify());
it('should return the expected data', async () => {
const response = await GetProjectScenario1(responsibleSceario1);
expect(response.headers['content-type']).toBe("application/json; charset=utf-8")
expect(response.status).toEqual(200);
expect(response.data).toEqual(ProjectJsonSucessfull);
});
})
afterAll(() => mockProvider.finalize())
})
Sed resquest with "/Project?responsible=teste.k6%40k6.com&Name=Teste%20para%20a%20pequisa"

Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components'

I am trying to send files to ipfs using a website in node-js. I am using the ipfs-http-client module. When i try to access the module using require I keep getting this error :
Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components' in the command prompt.
This the error message in the website :
Failed to compile
./src/components/App.js
Module not found: Can't resolve 'ipfs-http-client' in 'D:\Pro\src\components'
This error occurred during the build time and cannot be dismissed.
I installed the module using the command specified in the official docs -
"npm install --save ipfs-http-client" . I can see the module in my dependencies but still getting this error.
I am a complete newbie to all this. A little help would be much appreciated. Thanks in advance.
This is how I am accessing the module :
***import React, { Component } from 'react';
import logo from '../logo.png';
import './App.css';
const ipfsClient = require('ipfs-http-client');
const projectId = '*****';
const projectSecret = '***';
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const ipfs = ipfsClient.create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
class App extends Component {
constructor(props) {
super(props);
this.state={
buffer: null
};
}
captureFile=(event) => {
event.preventDefault()
const file = event.target.files[0]
const reader = new window.FileReader()
reader.readAsArrayBuffer(file)
reader.onloadend=() => {
this.setState({buffer: Buffer(reader.result) })
}
console.log(event.target.files)
}
onSubmit = (event) => {
event.preventDefault()
console.log("Submitting the form...")
ipfs.add(this.state.buffer, (error,result) => {
console.log('Ipfs result', result)
if(error){
console.error(error)
return
}
})
}***
Try using earlier version I have just tried it. Do the following :
npm uninstall --save ipfs-http-client
npm i --save ipfs-http-client#33.1.1
I do not know what the problem is with the updated version but this is a quick fix up for now. And will get your code running
Import it like this:
const ipfsClient = require('ipfs-http-client');
Then create the connection:
const ipfs = ipfsClient.create(https://ipfs.infura.io:5001);
To upload:
const uploadFile = await ipfs.add({ content: file });
Maybe you're missing the babel loaders I got this working using the following:
npm i ipfs-http-client#50.1.2 #babel/core --save
If you take a look at the package at the npm website, you'll see that the newer versions import the create-function as such:
import { create } from 'ipfs-http-client'
Using this, you can simply change your code to
import React, { Component } from 'react';
import logo from '../logo.png';
import './App.css';
import { create } from 'ipfs-http-client';
const projectId = '*****';
const projectSecret = '***';
const auth =
'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const ipfs = create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
class App extends Component {
...
}

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;
};

Mongoose Unexpected token u in JSON at position 0

I'm creating an AWS Lambda API with Node JS. There's a template for the db connection itself, but when I run a test in Lambda I get an error and I believe the problem is the connection itself.
Here's the error message I get with Lambda test:
START RequestId: 6b9eef97-9c54-44bc-8ecc-dfbec7e200e5 Version: $LATEST
2020-05-23T01:46:23.685Z 6b9eef97-9c54-44bc-8ecc-dfbec7e200e5 INFO => using new database connection
2020-05-23T01:46:23.689Z 6b9eef97-9c54-44bc-8ecc-dfbec7e200e5 ERROR (node:8) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
2020-05-23T01:46:23.726Z 6b9eef97-9c54-44bc-8ecc-dfbec7e200e5 ERROR (node:8) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
2020-05-23T01:46:23.828Z 6b9eef97-9c54-44bc-8ecc-dfbec7e200e5 ERROR Unhandled Promise Rejection {"errorType":"Runtime.UnhandledPromiseRejection","errorMessage":"SyntaxError: Unexpected token u in JSON at position 0","reason":{"errorType":"SyntaxError","errorMessage":"Unexpected token u in JSON at position 0","stack":["SyntaxError: Unexpected token u in JSON at position 0"," at JSON.parse ()"," at /var/task/handler.js:17:22"," at processTicksAndRejections (internal/process/task_queues.js:97:5)"]},"promise":{},"stack":["Runtime.UnhandledPromiseRejection: SyntaxError: Unexpected token u in JSON at position 0"," at process. (/var/runtime/index.js:35:15)"," at process.emit (events.js:310:20)"," at processPromiseRejections (internal/process/promises.js:209:33)"," at processTicksAndRejections (internal/process/task_queues.js:98:32)"]}
END RequestId: 6b9eef97-9c54-44bc-8ecc-dfbec7e200e5
REPORT RequestId: 6b9eef97-9c54-44bc-8ecc-dfbec7e200e5 Duration: 186.61 ms Billed Duration: 200 ms Memory Size: 1024 MB Max Memory Used: 34 MB
Unknown application error occurred
DB.js
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
let isConnected;
module.exports = connectToDatabase = () => {
if (isConnected) {
console.log("=> using existing database connection");
return Promise.resolve();
}
console.log("=> using new database connection");
return mongoose.connect(process.env.DB).then((db) => {
isConnected = db.connections[0].readyState;
});
};
Handler.js
"use strict";
const connectToDatabase = require("./db");
const Lead = require("./leads.model.js");
require("dotenv").config({ path: "./variables.env" });
module.exports.hello = (event, context, callback) => {
console.log("Hello World");
callback(null, "Hello World");
};
module.exports.create = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
connectToDatabase().then(() => {
Lead.create(JSON.parse(event.body))
.then((lead) =>
callback(null, {
statusCode: 200,
body: JSON.stringify(lead),
})
)
.catch((err) =>
callback(null, {
statusCode: err.statusCode || 500,
headers: { "Content-Type": "text/plain" },
body: "Could not create the lead.",
})
);
});
};
variables.env
DB=mongodb+srv://dbUser:password#api-jodqc.mongodb.net/test?retryWrites=true&w=majority
Whenever I see Unexpected token u in JSON at position 0, it usually means JSON.parse is trying to parse undefined. Looking at the code, I only see you executing parse in one spot
Lead.create(JSON.parse(event.body))
I'm guessing when you execute the Lambda, you're passing in an object that looks like a lead directly, so maybe something like below.
{
isALead: true
}
Instead, you need to test with an object that looks like
{
body: "{ \"isALead\": true }"
}

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