use encryptTransform in redux-persist, met a error: Unhandled Runtime Error, - react-redux

Too many re-renders. React limits the number of renders to prevent an infinite loop.
const persistConfig = {
key: 'xxxx',
storage: storage,
stateReconciler: autoMergeLevel2,
transforms: [
encryptTransform({
secretKey: 'xxxx',
onError: function (error) {
console.log("persistStore error:", error);
},
}),
],
};

Related

Lambda function is completed but I'm unable to query Aurora DB

Currently, I'm using a Lambda function, SSM and Aurora DB together.
I manage to get Aurora's credentials from SSM and the whole lambda is completed but I can't query the database. I took this tutorial as a reference which was also recommended by the aws support yet I'm still unable to use the Aurora Database
The following is my lambda code:
export async function handler (event:any)
{
try
{
console.log("Welcome to lambda")
const ssm = new SSM();
const username = await ssm
.getParameter({ Name:*** , WithDecryption: false })
.promise();
const password = await ssm
.getParameter({ Name:*** , WithDecryption: true })
.promise();
console.log("Before Connection")
let pool = mysql.createPool({
host: '***',
database: 'aurora-test1-us-mysql-multilevel',
user: username.Parameter?.Value,
password: password.Parameter?.Value,
port:3306
});
pool.getConnection(function(err, connection) {
// Use the connection
connection.query('SELECT * from feature', function (error, results, fields) {
console.log("result",results[0]);
// And done with the connection.
connection.release();
// Handle error after the release.
if (error)
console.log("Error: ",error)
else
console.log("result",results[0].emp_name);
});
});
let q = pool.query('SELECT * from feature')
console.log("Query",q)
return {
statusCode: 200,
body: "HELLO KIMOO!!! Welcome TO AURORA DB" + "Database Created2"
}
}
catch(err)
{
console.log("Error caught",err)
return {
statusCode: 500,
body: JSON.stringify({
message: 'Error: ' + err
})
}
}
}
The following is the the output for console.log("Query",q):
Query <ref *1> Query {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
_callback: undefined,
_callSite: Error
at Pool.query (/var/task/node_modules/mysql/lib/Pool.js:199:23)
at Runtime.<anonymous> (/var/task/index.js:48:26)
at Generator.next (<anonymous>)
at fulfilled (/var/task/index.js:5:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5),
_ended: false,
_timeout: undefined,
_timer: Timer { _object: [Circular *1], _timeout: null },
sql: 'SELECT * from feature',
values: undefined,
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null,
[Symbol(kCapture)]: false
}
NOTE:
There are no logs for console.log("result",results[0]);

Apollo Server Context Request Property Does Not Exist

Here's my Apollo Server definition.
const server = new ApolloServer({
schema,
context: (async ({ req }) => {
console.log(req);
return {};
}),
csrfPrevention: true,
cache: 'bounded',
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
ApolloServerPluginLandingPageLocalDefault({ embed: true }),
],
});
As we can see that auth property does exists in the req object but somehow when I tried to get the value, an error thrown Property 'auth' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' How can I retrieve the auth property?
<ref *2> IncomingMessage {
...,
auth: { sub: '1234567890', name: 'John Doe', iat: 1516239022 },
body: { query: 'query Query() {\n }\n}\n' },
_body: true,
length: undefined,
[Symbol(kCapture)]: false,
[Symbol(RequestTimeout)]: undefined
}
after a little bit try and error, I can solve this issue by cast the context request to express-jwt.Request type as the code shown below,
const server = new ApolloServer({
schema,
context: (({ req }: { req: Request }) => {
console.log(req.auth);
return {};
}),
csrfPrevention: true,
cache: 'bounded',
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
ApolloServerPluginLandingPageLocalDefault({ embed: true }),
],
});

How to use RTK Query in createSlice?

I want to process the data that I get from the request in the slice.
Because not all slices are async (but work with the same data), transformResponse is not suitable.
Is there anything you can suggest?
My code example:
Some RTK Query
export const currencyApi = createApi({
reducerPath: 'currencyApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://api.apilayer.com/exchangerates_data' }),
endpoints: (build) => ({
fetchCurrencyRates: build.query<IApiResponse, string>({
query: (currency) => ({
url: '/latest',
params: {
base: currency
},
headers: {
apikey: *SomeApiKey*
}
})
})
})
})
Slice where I want to use data from RTK requests
const initialState: ICurrencyState = {
currencyRates: {},
availableCurrencyOptions: [],
fromCurrency: '',
toCurrency: '',
exchangeRate: 0,
error: null
}
export const currencySlice = createSlice({
name: 'currency',
initialState,
reducers: {
//
}
})
Use Hooks in Components
You can send the received data to the slice via useEffect. Something like this:
const { data } = useFetchCurrencyRatesQuery();
useEffect(() => {
if (data !== undefined) {
dispatch(...)
}
}, [data])

Nest.js handling errors for HttpService

I'm trying to test NestJS's built in HttpService (which is based on Axios). I'm having trouble testing error/exception states though. In my test suite I have:
let client: SomeClearingFirmClient;
const mockConfigService = {
get: jest.fn((type) => {
switch(type) {
case 'someApiBaseUrl': {
return 'http://example.com'
}
case 'someAddAccountEndpoint': {
return '/ClientAccounts/Add';
}
case 'someApiKey': {
return 'some-api-key';
}
default:
return 'test';
}
}),
};
const successfulAdd: AxiosResponse = {
data: {
batchNo: '39cba402-bfa9-424c-b265-1c98204df7ea',
warning: '',
},
status: 200,
statusText: 'OK',
headers: {},
config: {},
};
const failAddAuth: AxiosError = {
code: '401',
config: {},
name: '',
message: 'Not Authorized',
}
const mockHttpService = {
post: jest.fn(),
get: jest.fn(),
}
it('Handles a failure', async () => {
expect.assertions(1);
mockHttpService.post = jest.fn(() => of(failAddAuth));
const module: TestingModule = await Test.createTestingModule({
providers: [
{
provide: ConfigService,
useValue: mockConfigService,
},
{
provide: HttpService,
useValue: mockHttpService,
},
SomeClearingFirmClient,
],
}).compile();
client = module.get<SomeClearingFirmClient>(SomeClearingFirmClient);
const payload = new SomeClearingPayload();
try {
await client.addAccount(payload);
} catch(e) {
console.log('e', e);
}
});
And my implementation is:
async addAccount(payload: any): Promise<SomeAddResponse> {
const addAccountEndpoint = this.configService.get('api.someAddAccountEndpoint');
const url = `${this.baseUrl}${addAccountEndpoint}?apiKey=${this.apiKey}`;
const config = {
headers: {
'Content-Type': 'application/json',
}
};
const response = this.httpService.post(url, payload, config)
.pipe(
map(res => {
return res.data;
}),
catchError(e => {
throw new HttpException(e.response.data, e.response.status);
}),
).toPromise().catch(e => {
throw new HttpException(e.message, e.code);
});
return response;
}
Regardless of whether I use Observables or Promises, I can't get anything to catch. 4xx level errors sail on through as a success. I feel like I remember Axios adding some sort of config option to reject/send an Observable error to subscribers on failures... but I could be imagining that. Am I doing something wrong in my test harness? The other StackOverflow posts I've seen seem to say that piping through catchError should do the trick, but my errors are going through the map operator.
Your mockHttpService seems to return no error, but a value:
mockHttpService.post = jest.fn(() => of(failAddAuth));
What of(failAddAuth) does is to emit a value(failAddAuth) and then complete.
That's why the catchError from this.httpService.post(url, payload, config) will never be reached, because no errors occur.
In order to make sure that catchError is hit, the observable returned by post() must emit an error notification.
You could try this:
// Something to comply with `HttpException`'s arguments
const err = { response: 'resp', status: '4xx' };
mockHttpService.post = jest.fn(() => throwError(err));
throwError(err) is the same as new Observable(s => s.error(err))(Source code).

Lambda function – GET doesn't return anything

I am completely new to The Serverless Framework and AWS lambda.
When making a GET request to http://localhost:3000/user/1e89a3f0-d170-11e9-94bd-91e9ae84f3e9 I would expect a response being send back to the browser with a valid JSON object matching the Key. Like the only getting logged out to the console. And not empty document.
Am I returning incorrectly? I am having difficulties debugging this, I don’t now if the problem is with my lambda function, or what it is.
Thank you.
console.log statement
{
email: 'i#am.com',
password: '$argon2i$v=19$m=4096,t=3,p=1$IIICgcMqbUA7wFpEMqb/GA$ENScjko+Y8pruQsTiE6qN81QAJfAPX/T116RQZqe347Y1p0rez4KhKaEulMeabKKiu8',
id: '1e89a3f0-d170-11e9-94bd-91e9ae84f3e9'
}
Here is the get handler in question.
users/get.js
const AWS = require("aws-sdk");
const dynamoDb = new AWS.DynamoDB.DocumentClient({
region: "localhost",
endpoint: "http://localhost:8000"
});
module.exports.get = async event => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id
}
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
return;
}
console.log(result.Item); // logs successfully to the console.
return {
// doesn't return a response.
statusCode: 200,
body: JSON.stringify(result.Item)
};
});
};
serverless.yml
# EXCERPT
functions:
get:
handler: users/get.get
events:
- http:
method: get
path: user/{id}
cors: true
resources:
Resources:
UsersDynamoDbTable:
Type: "AWS::DynamoDB::Table"
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:provider.environment.DYNAMODB_TABLE}
custom:
dynamodb:
stages:
- dev
start:
port: 8000
inMemory: true
sharedDb: true
noStart: true
You should either use the callback argument to return a response:
module.exports.get = (event, context, callback) => {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id,
},
};
dynamoDb.get(params, (error, result) => {
if (error) {
console.error(error);
callback({
statusCode: 500,
body: 'Unable to get item',
});
}
console.log(result.Item);
callback(null, {
statusCode: 200,
body: JSON.stringify(result.Item),
});
});
};
Or use promises:
module.exports.get = async event => {
try {
const params = {
TableName: process.env.DYNAMODB_TABLE,
Key: {
id: event.pathParameters.id,
},
};
const result = await dynamoDb.get(params).promise();
console.log(result.Item);
return {
statusCode: 200,
body: JSON.stringify(result.Item),
};
} catch (error) {
console.error(error);
return {
statusCode: 500,
body: 'Unable to get item',
};
}
};

Resources