error calling Action in store with nuxt-socket.io err_action_access_undefined - socket.io

I'm having problems calling actions in the store when I configure the nuxt-socket.io in the project, I'm configuring the nuxt-socket.io in the nuxt.config.js and calling the connection in the component according to the nuxt-socket.io documentation ( https://nuxt-socket-io.netlify.app/usage ), but when this configuration is performed, the components can no longer call the actions of the store.
I'm using vuex and vuex-module-decorators.
Config nuxt.config.js:
io: {
sockets: [
{
name: 'home',
url: 'http://url-server-backend.com',
default: true,
}
]
},
Config component:
async beforeMount(){
const token = this.$cookies.get('authToken');
this.socket = this.$nuxtSocket({
name: 'home',
channel: '/socket-io',
persist: true,
teardown: true,
reconnection: false,
extraHeaders: {
Authorization: token
}
});
},
Error:
Image Error action

Related

There is no matching message handler error in NestJs TCP E2E test

I'm playing around with Microservice architecture using NestJs. I've made a simplified repository with a few services that communicate over TCP with a mix of message and event patterns.
I have moved on to writing E2E tests for the using Supertest, and while I'm able to run the needed microservice, the requests respond with {"error": "There is no matching message handler defined in the remote service.", "statusCode": 500}
GatewayService: HTTP Rest Api where the E2E tests are run. Calls the service
AuthService: NestJs microservice running on 0.0.0.0:3001 by default
configService: a simple service that returns information needed to set up the services, like host and port. I have tried eliminating it from the test and hardcoding the values.
The E2E test file
import { INestApplication, ValidationPipe } from '#nestjs/common';
import { ClientProxy, ClientsModule, Transport } from '#nestjs/microservices';
import { Test, TestingModule } from '#nestjs/testing';
import * as request from 'supertest';
import { configService } from '../src/config.service';
import { RpcExceptionFilter } from '../src/filters/rpc-exception.filter';
import { AppModule } from './../src/app.module';
describe('AuthenticationController (e2e)', () => {
let app: INestApplication;
let authClient: ClientProxy;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
AppModule,
ClientsModule.register([
{
...configService.getServiceConfigs().authService,
transport: Transport.TCP,
},
]),
],
}).compile();
// Setup the app instance
app = moduleFixture.createNestApplication();
// Setup the relevant micorservice(s)
app.connectMicroservice({
transport: Transport.TCP,
name: configService.getServiceConfigs().authService.name,
options: configService.getServiceConfigs().authService.options,
});
app.startAllMicroservices();
// Add request validation
app.useGlobalPipes(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
}),
);
// Add needed filters
app.useGlobalFilters(new RpcExceptionFilter());
await app.init();
authClient = app.get(configService.getServiceConfigs().authService.name);
await authClient.connect();
console.log('authClient', authClient);
});
describe('POST /auth/login', () => {
it('Should return status 200 and a user object with access token', () => {
return (
request(app.getHttpServer())
.post('/auth/login')
.send({ username: 'exmple#user.com', password: 'password' })
// .expect(200)
.expect((response) => {
console.log('response', response.body);
expect(response.body).toHaveProperty('id');
expect(response.body).toHaveProperty('username');
expect(response.body).toHaveProperty('accessToken');
})
);
});
});
afterAll(async () => {
await app.close();
await authClient.close();
});
});
I have attempted adding a provider which I've used before when working with Grpc as the transport layer (this is TCP). Didn't change anything.
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
...
providers: [
{
provide: 'AUTH_SERVICE',
useFactory: () => {
return ClientProxyFactory.create({
transport: Transport.TCP,
options: { host: 'localhost', port: 3001 },
});
},
},
],
I know that the microservice starts up and the gateway service is able to connect to it since when printing the authClient: Client proxy it returns a correct object with URL 0.0.0.0:3001. If I change the URL, or the name of the service in any part of the setup then errors about missing providers show, further confirming that it is supposedly correctly set up.
One of the best guides I've found on this matter. Sadly it doesn't work for my code.

RTK type Error when using injectedEndpoints with openApi

I define config file for openApi to create automatically endpoints with types:
const config: ConfigFile = {
schemaFile: 'https://example.com/static/docs/swagger.json',
apiFile: './api/index.ts',
apiImport: 'api',
outputFile: './api/sampleApi.ts',
exportName: 'sampleApi',
hooks: true,
};
export default config;
I used :
"#rtk-query/codegen-openapi": "^1.0.0-alpha.1"
"#reduxjs/toolkit": "^1.7.2",
Then I define an index.tsx that has
export const api = createApi({
baseQuery: axiosBaseQuery({ baseUrl: '' }),
endpoints: () => ({}),
});
and So I generate successfully my sampleApi.tsx file with all of endpoints and types.
like here:
const injectedRtkApi = api.injectEndpoints({
endpoints: (build) => ({
postUsersCollections: build.mutation<
PostUsersCollectionsApiResponse,
PostUsersCollectionsApiArg
>({
query: (queryArg) => ({
url: `/users/collections`,
method: 'POST',
body: queryArg.postCollectionBody,
}),
}),
getUsersCollections: build.query<
GetUsersCollectionsApiResponse,
GetUsersCollectionsApiArg
>({
query: (queryArg) => ({
url: `/users/collections`,
params: { name: queryArg.name },
}),
}),
overrideExisting: false,
});
export const {
usePostUsersCollectionsMutation,
useGetUsersCollectionsQuery
} = injectedRtkApi;
when in a component I use hook function useGetUsersCollectionsQuery as bellow I got an error that TypeError: Cannot read properties of undefined (reading 'subscriptions'). There is no lint typescript error related to typescript in my project.
const { data: collectionData = [] } = useGetUsersCollectionsQuery({});
It's Interesting that this hook called and I see API call in network tab but immediately I got this error. I remove this line and error is disappeared.
And Also for mutation hook I send data within it but I got 400 error. as Below:
const [postCollection, { data: newCollect }] =
usePostUsersCollectionsMutation();
...
const handleCreateItem = async () => {
const response: any = await postCollection({
postCollectionBody: { name: 'sample' },
}); }
Please help me! I really thanks you for taking time.
Finally I resolved it!
I should define reducerPath as this:
export const api = createApi({
reducerPath: 'api', <=== add this and define `api` in reducers
baseQuery: axiosBaseQuery({ baseUrl: '' }),
endpoints: () => ({}),
});

AWS Lambda handle authorization headers error

For my project, I'm utilizing AWS Lambda and Graphql. I used apollo-server-lambda for this project. For this project, I created custom headers. And I added a simple condition to throw an error if there is no 'event.headers.authorization'. When the app is launched in a local environment, the error is thrown correctly. But the issue is that I'm not sure how I'm going to put my authorisation in if it's continuously throwing me off. I'm certain my implementation is incorrect. I'm not sure what the best method is for obtaining authorization.
It should be put like this:
.
This is my Lambda
import * as R from 'ramda';
import { AuthenticationError, ForbiddenError } from 'apollo-server-lambda';
export const authToken = (token: string) => {
if (token === 'HELLO') {
return true;
} else {
throw new AuthenticationError('No authorization header supplied');
}
};
const lambda =
(lambdaFunc: AWSLambda.Handler): AWSLambda.Handler =>
(event, context, callback) => {
const { authorization } = event.headers;
if (R.isNil(authorization))
throw new ForbiddenError('You must be authenticated'); // always thorws me error
return authToken(event.headers.authorization);
return lambdaFunc(event, context, callback);
};
export default lambda;
This is my graphql
import { ApolloServerPluginLandingPageGraphQLPlayground } from 'apollo-server-core';
import { ApolloServer} from 'apollo-server-lambda';
import schema from '../graphql/schema';
import resolvers from '../resolvers';
import lambda from '../utils/lambda';
const server = new ApolloServer({
typeDefs: schema,
resolvers,
debug: false,
plugins: [ApolloServerPluginLandingPageGraphQLPlayground()],
introspection: true,
});
export default lambda(
server.createHandler({
expressGetMiddlewareOptions: {
cors: {
origin: '*',
credentials: true,
allowedHeaders: ['Content-Type', 'Origin', 'Accept', 'authorization'],
optionsSuccessStatus: 200,
maxAge: 200,
exposedHeaders: ['authorization'],
},
},
})
);
This is YAML file
functions:
graphql:
handler: src/handlers/graphql.default
events:
- http:
path: ${env:api_prefix}/graphql
method: get
cors: true
- http:
path: ${env:api_prefix}/graphql
method: post
cors: true

How to configure proxy in Vite?

I was trying to follow the docs and created vite.config.js like this:
const config = {
outDir: '../wwwroot/',
proxy: {
// string shorthand
'/foo': 'http://localhost:4567',
// with options
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
};
export default config;
And tried to test it with following calls:
fetch('/foo');
fetch('/api/test/get');
I was expecting to have actual requests as http://localhost:4567/foo and http://jsonplaceholder.typicode.com/test/get
But both of them had my dev server as an origin like this: http://localhost:3000/foo and http://localhost:3000/api/test/get
Did I misunderstand it? How proxies should work?
I also created an issue in the Vite repo but it was closed and I did not understand the closing comment.
Turns out it's needed to specify secure flag to false like this:
proxy: {
'/api': {
target: 'https://localhost:44305',
changeOrigin: true,
secure: false,
ws: true,
}
}
Related github issue
Based on the Vite Config you need to specify it via server -> proxy inside vite.config.js:
export default defineConfig({
server: {
proxy: {
"/api": {
target: "https://your-remote-domain.com",
changeOrigin: true,
secure: false,
},
},
},
// some other configuration
})
For debugging I highly recommend to add event listeners to the proxy, so you can see how the requests are transformed, if they hit the target server, and what is returned.
proxy: {
'/api': {
target: 'https://localhost:44305',
changeOrigin: true,
secure: false,
ws: true,
configure: (proxy, _options) => {
proxy.on('error', (err, _req, _res) => {
console.log('proxy error', err);
});
proxy.on('proxyReq', (proxyReq, req, _res) => {
console.log('Sending Request to the Target:', req.method, req.url);
});
proxy.on('proxyRes', (proxyRes, req, _res) => {
console.log('Received Response from the Target:', proxyRes.statusCode, req.url);
});
},
}
}
proxy will be an instance of 'http-proxy',
Please see for further info https://github.com/http-party/node-http-proxy#options

I can't access $auth.user from auth plugin or middleware using nuxtjs and getting api from laravel

My goal is that i want to access $auth.user.roles from plugin and middleware to be able to not let this role reach the other role page.
what is expected is that when console.log($auth.user) it gives me the user data (id,...) and when a console.log($auth.loggedIn)it gives me true.
My problem is that i can't access $auth.user from plugin and middleware to chieve that which $auth.user = null and $auth.loggedIn = false while im logged in.
here is my nuxt.config.js:
axios: {
baseURL: env.parsed.API_URL || 'http://localhost:3000/api',
debug:true},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/auth/signin',
method: 'post',
propertyName: 'data.token'
},
user: {
url: '/auth/me',
method: 'get',
propertyName: 'data'
},
logout: {
url: '/auth/signout',
method: 'post'
},
tokenRequired: true,
tokenType: 'bearer',
globalToken: true,
autoFetchUser: true
},
},
},
redirect:false,
plugins: [ '~/plugins/roles.js' ]
},
here is my plugins/roles.js :
export default function ({app}) {
const username = app.$auth.user
if (!app.$auth.loggedIn) {
return console.log(username ,'roles plugin ', app.$auth.loggedIn)
}}
here is the res: null roles plugin false
the same result using this code:
export default function ({$auth}) {
const username = $auth.user
if (!app.$auth.loggedIn) {
return console.log(username ,'roles plugin', $auth.loggedIn)
}}
Ps:when i use $auth.user in my vue pages it gives me the whole user data (thats wonderfull)
I searched about this problem so i found common answers like :
*Change the user propertyName to false.
*reinstall node_modules.
but same result
Thank you every one <3

Resources