does the amplify graphql api-key inside a lambda function expire? - graphql

I have a time triggered lambda function in amplify and it works fine:
url: process.env.API_P2PCHAKRA_GRAPHQLAPIENDPOINTOUTPUT,
method: 'post',
headers: {
'x-api-key': process.env.API_P2PCHAKRA_GRAPHQLAPIKEYOUTPUT
},
data: {
query: print(listorderstatuss ),
variables: {
limit: 100,
nextToken: nextToken
}
}
}) ;
my question is do I have to worry about api-key expiration ? Or is amplify/AWS doing something in the background I don't understand.

Related

Passing array from POSTMAN and AJAX is different when received by ExpressJS

I am new to Express but not in programming. I am trying to pass an array via ajax from my frontend to express. On my postman, this is the array I am sending:
{
"userIds": ["xxxxxxxxxxxxxxxxxx"],
"type": "user"
}
and express is receiving req.body as:
{
userIds: [ 'xxxxxxxxxxxxxxxxxx' ],
type: 'user'
}
When I do this in Ajax:
data = {
userIds: ["xxxxxxxxxxxxxxxxxx"],
type: "user",
};
$.ajax({
type: "POST",
url: url,
headers: headerParams,
data: data,
success: function (room) {
console.log("room", room);
},
error: function (error) {
console.log("error", error);
},
});
Express is receiving:
[Object: null prototype] {
'userIds[]': 'xxxxxxxxxxxxxxxxxx',
type: 'user'
}
What am I doing wrong here? Or how should I mutate my req.body to get the desired output?
Note: I cannot do req.body.Foreach since it is saying forEach is not a function.
Note 2: req.body.userIds returns undefined
My best guess, Middleware body-parser to your rescue.
You can then access it as req.body.userIds, which will be an Array.

Catch a request after POST

I have a component in which a user can add a number of hours worked and post that to the server. For testing I want to remove the added hours so I can run the test again (the user cannot add hours on a day that already has hours).
There's a response on the request which has the id of the added hours. I can use a end point with that id to remove them. So the question is how do I gain access to the response of a request in Cypress?
it('Removed saved hours', () => {
cy.intercept('GET', 'api/v0/work-hours/?filter[job_id]=21173&filter[week_id]=202133').as('savedHours')
cy.get('[data-cy=jobs]').children('div').first().click()
cy.wait('#savedHours').then((res) => {
cy.request({
method: 'DELETE',
url: 'https://***/api/v0/work-hours',
headers: {
Authorization: res.request.headers.authorization,
'Content-Type': 'application/vnd.api+json',
Accept: 'application/vnd.api+json'
},
body: {
data: {
data: {
attributes: { ust_id: res.response.body.data[0].id },
type: 'work_hours'
}
}
}
})
})
})
Got it working. What's important is that you first initiatie the interceptor, then do the call and then you can handle the data.

How store user from this.$auth.fetchUser()?

I have a Nuxtjs app which authenticates fine. But I need the user details for filling out a form automatically. I see that the app calls /user endpoint on every reload. I want to insert a $store in its callback to store the user data in $store.
computed: {
getUser () {
return this.$store.state.user.user;
}
},
methods: {
setUser (data) {
this.$store.commit('user/add', data)
},
}
NUXT Config:
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/auth/login',
method: 'post',
propertyName: 'access_token'
},
logout: {
url: '/auth/logout',
method: 'post'
},
user: {
url: '/auth/user',
method: 'get',
propertyName: false
},
tokenRequired: true
}
}
}
}
Is it possible to intercept the $auth.fetchUser or whatever method $auth is using to fetch the api/user endpoint on every reload?
I solved it by using auth and vuex methods. I don't need to intercept the call. Just use
this.$auth.user
or
this.$store.state.auth.user;
Learning Nuxt/Vuejs is fun.

GRAPHQL mutation with axios

Im using graphCMS and I want to make a post request using axios.
I can actually do a mutation in postman.
see example: https://prnt.sc/sjsj3p
but when in actual coding using axios, I cant get the proper format of the query.
I search some graphql mutation but it seems that the graphcms has a different format(Im not sure).
axios({
method: 'POST',
url: apiUrl,
headers: {
'Content-Type': 'application/json',
'Authorization': graphcmsBearerKey
},
data: {
query: `
mutation CreateCompanyCustomization() {
createCompanyCustomization(
data: {
domain: "sampledomain.com"
}
)
}
`
}
}).then(res => {
console.log(res)
}).catch(err => {
isErrorState('ERROR STATE')
console.log(err)
})
any suggestion? Thanks!

Getting 502 response and 'has been blocked by CORS policy' running a simple fetch request to my lambda function

Building a serverless web app on AWS with the serverless framework, I get a CORS error with a 502 response code authenticating against an AWS Cognito user pool
GET https://URL.amazonaws.com/dev/asset/ID-1178 502
index.html:1 Access to fetch at 'https://URL.amazonaws.com/dev/asset/PO-TIENDA1178' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
index.js:109 Uncaught (in promise) TypeError: Failed to fetch
An almost identical request works for another function.
And here are both ajax requests sent from the frontend:
// working just fine
async function getAllAssets() {
const getAssetsUrl = _config.api.invokeUrl + "/assets"
const response = await fetch(getAssetsUrl, {
headers: {
Authorization: authToken
},
type: "GET",
dataType: 'json',
crossDomain: true
})
}
// not working, throwing the error described above
async function getOneAsset() {
const getAssetsUrl = _config.api.invokeUrl + "/asset/" + "ID-1178"
const response = await fetch(getAssetsUrl, {
headers: {
Authorization: authToken
},
type: "GET",
dataType: 'json',
crossDomain: true
})
}
I run both functions onDocReady in the same window.
Here are the definitions in serverless.yaml:
# WORKS 👌🏽
getAssets:
name: ${self:service}-${self:provider.stage}-get-assets
handler: handler.getAssets
role: InventoryLambdaRole
events:
- http:
path: /assets
method: get
cors: true
authorizer:
arn: arn:aws:cognito-idp:eu-west-1:HARDCODED:ARN
# doesn't work
getAsset:
name: ${self:service}-${self:provider.stage}-get-asset
handler: handler.getAsset
role: InventoryLambdaRole
events:
- http:
path: /asset/{assetId}
method: get
cors: true
authorizer:
arn: arn:aws:cognito-idp:eu-west-1:HARDCODED:ARN
And here goes my function implementations in the handler.js:
// get all assets works fine:
module.exports.getAssets = function(event, context, callback) {
const params = {
TableName : 'Assets',
Select: 'ALL_ATTRIBUTES',
}
const request = documentClient.scan(params, function(err, data) {
if (err) {
console.log("Error", err)
} else {
const itemCount = data.Count
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
itemCount: itemCount,
assets: data
}),
}
callback(null, response);
}
})
}
// get one asset doesn't work:
module.exports.getAsset = function(event, context, callback) {
const params = {
TableName : 'Assets',
Key: {
AssetId: event.pathParameters.assetId // also tried to just hardcode it like this: 'ID-1178'
}
}
const request = documentClient.get(params, function(err, data) {
if (err) {
console.log("Error", err)
} else {
const response = {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
},
body: JSON.stringify({
asset: data
}),
}
callback(null, response);
}
})
Although it's a CORS error, as you can see the origin headers are provided, and I found that in combination with the 502 status it might be something before the CORS, e.g. a problem in the function or with authorization. However, I can't see any problems with them so far.
The serverless function itself works as well when invoke it locally:
npm run sls -- invoke local --function getAsset -p test.json
Do you have any ideas what could be the issue or how to debug it?
Your issue may be as simple as having dynamodb:GetItem. This is a different permission than what listing all (ie query or scan) would be

Resources