So i am facing a very weird issue. I have a react native app that was working fine until yesterday night. Suddenly then my aws s3 connections stopped working. We had made no changes in the code to that code in 2 months which is why im confused.
Here is my CloudService.js
import React ,{useState} from 'react';
import AWS from 'aws-sdk'
export const S3_BUCKET_CAROUSEL ='carouselnews';
export const S3_BUCKET_ADVISORS = 'advisorsdata';
const REGION ='ap-south-1';
AWS.config.update({
accessKeyId: 'xxxxxx',
secretAccessKey: 'xxxxxx'
})
export const getCarouselData = () => {
const bucket = new AWS.S3({
params: { Bucket: S3_BUCKET_CAROUSEL},
region: REGION,
})
const S3_URL = `https://${S3_BUCKET_CAROUSEL}.s3.${REGION}.amazonaws.com/`
return bucket.listObjects().promise();
}
export const getS3URL = (bucket) => {
return `https://${bucket}.s3.${REGION}.amazonaws.com/`
}
Calling it in my Home.js like this:
(Gets executed inside useEffect but i tried moving it outside into a button too)
getCarouselData()
.then(data => {
if (data) {
var s3_url = getS3URL(S3_BUCKET_CAROUSEL);
var items = data.Contents;
items.forEach((item, index) => {
if (index > 5) {
return;
}
setcarouselItems(oldArray => [
...oldArray,
{
id: index + 1,
url: `${s3_url}${item.Key}`,
},
]);
});
}
setTimeout(() => {
setcarouselLoaded(true);
}, 4000);
})
.catch(err => {
console.log(err);
})
.finally(zz => {
console.log("whatttt")
})
Basically when the method runs, it does not return anything. Doesnt go in the catch either and i tried putting try catch inside, even there nothing happens
I checked my credential keys in AWS IAM to see if theres a problem there but according to that my keys were not used after last night atall!
Some little info, when i try to print just the bucket object, it does give a result saying that there is some interaction going on with AWS i think
Heres the response when i do console.log(bucket)
{"CALL_EVENTS_BUBBLE": [Function CALL_EVENTS_BUBBLE], "MONITOR_EVENTS_BUBBLE": [Function EVENTS_BUBBLE], "_clientId": 27, "_events": {"apiCall": [[Function CALL_EVENTS_BUBBLE]], "apiCallAttempt": [[Function EVENTS_BUBBLE]]}, "config": {"apiVersion": null, "apiVersions": {}, "clientSideMonitoring": false, "computeChecksums": true, "convertResponseTypes": true, "correctClockSkew": false, "credentialProvider": null, "credentials": {"accessKeyId": "AKIAXERRWBISWIDH64XH", "expireTime": null, "expired": false, "refreshCallbacks": [Array], "sessionToken": undefined}, "customUserAgent": null, "dynamoDbCrc32": true, "endpoint": "s3.ap-south-1.amazonaws.com", "endpointCacheSize": 1000, "endpointDiscoveryEnabled": undefined, "hostPrefixEnabled": true, "httpOptions": {"timeout": 120000}, "logger": null, "maxRedirects": 10, "maxRetries": undefined, "paramValidation": true, "params": {"Bucket": "carouselnews"}, "region": "ap-south-1", "retryDelayOptions": {}, "s3BucketEndpoint": false, "s3DisableBodySigning": true, "s3ForcePathStyle": false, "s3UsEast1RegionalEndpoint": "legacy", "s3UseArnRegion": undefined, "signatureCache": true, "signatureVersion": "v4", "sslEnabled": true, "stsRegionalEndpoints": "legacy", "systemClockOffset": 0, "useAccelerateEndpoint": false, "useDualstackEndpoint": false, "useFipsEndpoint": false}, "endpoint": {"host": "s3.ap-south-1.amazonaws.com", "hostname": "s3.ap-south-1.amazonaws.com", "href": "https://s3.ap-south-1.amazonaws.com/", "path": "/", "pathname": "/", "port": 443, "protocol": "https:"}, "isGlobalEndpoint": false}
The network call for the aws call:
Related
In the code below I want to validate the request body with a schema from zod, currently, it will fail and catch. This is because req.body is returning a ReadableStream<Uint8Array> and not the object that it expects to parse.
export default async function middleware(req: NextRequest, res: NextResponse) {
const { pathname } = req.nextUrl;
if (pathname.startsWith('/api/user/create')) {
try {
createUserSchema.parse({
body: req.body,
params: req.nextUrl.searchParams,
});
return NextResponse.next();
} catch (error: any) {
console.log(req.body);
return NextResponse.json(
{ success: false, message: error },
{ status: 422, headers: { 'content-type': 'application/json' } }
);
}
}
return NextResponse.next();
}
this below is the output of the console.log(req.body);
<ref *1> ReadableStream {
_state: 'readable',
_reader: undefined,
_storedError: undefined,
_disturbed: false,
_readableStreamController: ReadableStreamDefaultController {
_controlledReadableStream: [Circular *1],
_queue: S {
_cursor: 0,
_size: 0,
_front: { _elements: [], _next: undefined },
_back: { _elements: [], _next: undefined }
},
_queueTotalSize: 0,
_started: false,
_closeRequested: false,
_pullAgain: false,
_pulling: false,
_strategySizeAlgorithm: [Function],
_strategyHWM: 1,
_pullAlgorithm: [Function],
_cancelAlgorithm: [Function]
}
}
I did some research and found that I need to run some kind of conversion method on this ReadableStream. The problem is that most of these include the Buffer module which cannot be run on the Edge and therefore cannot work in the middleware.ts. Is there perhaps a polyfill that I can use?
"next": "^13.0.7"
Node v16.17.0
Next.js middleware does not work the same as an Express middleware because it only runs on navigation and does not act as a catch-all for your API endpoints.
As per the documentation, you can only access cookies, access/modify request headers and perform redirects and rewrites using this feature.
You can use
const body = await req.json()
I am trying to integrate paytm in react native. but the problem is when I tap on pay button (call call_api) but then processing screen is coming and suddenly app navigate to current screen where I define pay button. please help here is my code
call_api = () => {
fetch("https://XXXXXXXXXXXXXXX", {
method: "POST",
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json",
},
body: JSON.stringify([
{
mobile_no: "XXXXXx",
user_id: "XX",
patient_name: "XXXx",
},
]),
})
.then((returnValue) => returnValue.json())
.then((response) => {
console.log("this checksum api esponse" + JSON.stringify(response));
this.setState({ order_id: response[0].data.order_id });
this.setState({ checksum: response[0].data.checksumhash });
this.pay();
});
};
pay = () => {
const details = {
//mode: "Production", // 'Staging' or 'Production'
mode: "Production",
MID: "XXXXXXXXXXXXXXX",
INDUSTRY_TYPE_ID: "Retail",
WEBSITE: "APPSTAGING",
CHANNEL_ID: "WAP",
TXN_AMOUNT: "1", // String
ORDER_ID: this.state.order_id, // String
// EMAIL: email, // String
// MOBILE_NO: mobile, // String
CUST_ID: "CUSTOMER_1", // String
CHECKSUMHASH: `${this.state.checksum}`, //From your server using PayTM Checksum Utility
CALLBACK_URL:
"https://securegw.paytm.in/theia/paytmCallback?ORDER_ID=" +
`${this.state.order_id}`,
// CALLBACK_URL: `https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=<${this.state.order_id}>`,
};
Paytm.startPayment(details);
console.log(details);
};
Please make sure that you have Paytm Staging app installed on your device. You can get the same from the link mentioned on Paytm Developer Portal
I need to do a new api in order to send an email with sendgrid. I followed the official doc and other examples so I did:
config/plugins
module.exports = ({ env }) => ({
email: {
provider: 'sendgrid',
providerOptions: {
apiKey: env('SENDGRID_API_KEY'),
},
settings: {
defaultFrom: 'juliasedefdjian#strapi.io',
defaultReplyTo: 'juliasedefdjian#strapi.io',
},
},
});
then I did a new folder named email in api folder
api/email/config/routes.json
{
"routes": [
{
"method": "POST",
"path": "/email",
"handler": "email.index",
"config": {
"policies": []
}
}
]
}
finally under api/email/controllers/email.js
const { default: createStrapi } = require('strapi');
module.exports = {
index: async (ctx) => {
//build email with data from ctx.request.body
await createStrapi.plugins['email'].services.email.send({
to: 'email#email.com',
from: 'email#email.com',
replyTo: 'email#email.com',
subject: 'test',
text: 'test',
});
ctx.send('Email sent!');
},
};
The real problem is that /email api returns me a 403 even if I did this from the dashboard:
I have done many APIs with strapi but I have never sent emails with it.
Is there a way to add permissions from the code? I have to say that if I use GET method it works, but I need to do it with a POST method, which doesn't. Did I miss something?
I have using Apollo-client. I can see the data on network tab on chrome, also on edge. But When we console it, some object fields are covert automatically by NULL.
Here is my apollo config:
link: ApolloLink.from([errorLink, uploadLink]),
cache: new InMemoryCache(),
defaultHttpLink: false,
connectToDevTools: true,
});
apollo.defaultOptions = {
watchQuery: {
fetchPolicy: "network-only",
errorPolicy: "ignore",
},
query: {
fetchPolicy: "network-only",
errorPolicy: "all",
},
};
export default apollo;```
[![snap of console][1]][1]
[![snap of network tab][2]][2]
[1]: https://i.stack.imgur.com/wqKJX.png
[2]: https://i.stack.imgur.com/J3m2i.png
According to the API documentation, to receive json as formData from a POST request, one must use body-parser. I have declared it in the gateway service but I can still not receive the formData in my action.
api.service.js
module.exports = {
name: "api",
mixins: [ApiGateway],
settings: {
port: process.env.PORT || 3000,
routes: [{
path: "/api",
aliases: {
"POST users": "users.insertUser",
},
//The API Documentation recomends using the body-parser here
bodyParsers: {
json: true,
urlencoded: { extended: true }
},
}],
// In some example they also set the body-parser here
bodyParsers: {
json: true,
urlencoded: { extended: true }
},
},
};
In the actions service.insertUser action I am supposed to receive the
req.body as ctx.params, however it is always empty
My users.service.js
actions: {
insertUser: {
handler(ctx) {
this.logger.info("posting", ctx.params); // -> prints {} instead of the formData
}
}
have you tried giving params
insertUser: {
auth: "required",
params: {
function_id: { type: "string" },
role_id: { type: "string" },
},
handler(ctx) { ctx.params.role_id
send post data with content-type:application/json