How to extend AdonisJS Response class? - javascript

When a user creates a post in my RESTful application, I want to set the response status code to 201.
I followed the documentation and created start/hooks.js as follows:
'use strict'
const { hooks } = require('#adonisjs/ignitor')
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', (status) => {
this.status(status).send(status)
})
})
Now in my PostController.js, I have this:
async store( {request, response, auth} ) {
const user = await auth.current.user
response.sendStatus(201)
}
But I am getting 500 HTTP code at this endpoint.
What am I doing wrong?
I noticed when I run Response.hasMacro('sendStatus') I get false.

In fact adonis already have this out of the box for all response codes...
Just write response.created(.....).
You can also use for example: .badRequest(), .notFound(), etc...
More info on: https://adonisjs.com/docs/4.1/response#_descriptive_methods

I solved this problem yesterday:
hooks.after.httpServer(() => {
const Response = use('Adonis/Src/Response')
Response.macro('sendStatus', function (status) => {
this.status(status).send(status)
})
})

Related

How to fix the Request failed with status code 500 when reload page in react

The problem here is when every time I reload the page I'm getting this error.
which is the Uncaught (in promise) Error: Request failed with status code 500.
here's my code in list.tsx
const [state, setState] = useState([]);
const { getRoom } = useRoom();
const fetchData = async () => {
return getRoom().then((res) => setState(res['data'].data));
}
useEffect(() => {
(async function fetchData() {
await fetchData();
})();
})
code for room.tsx
function useRoom() {
const creds = useCredentials();
Axios.defaults.baseURL = serverConfig[creds.server].api;
return {
getRoom: (params?: object) => Axios.get(`${API_URL}/room` + (params ? getQueryParams(params) : ''))
};
}
500 is an error code servers produce. That's not necessarily something you can fix on the client. You'll need to understand which request the server returns a 500 to and why. Then maybe you can change something on the client (e.g. a malformed request). Or maybe you'll need to change something on the server.
Either way, looking only at the client-side JS code won't help you fix this.

How to use AsyncData with Promise.all to get data from multiple api's works client side but causes nginx to 504

I'm currently converting a vue application to use the NUXT framework. To add support for SSR to my application and have come across the following issue when trying to use asyncData with multiple data sources on a single page.
I'm trying to setup asyncData to get data from 2 separate data sources that are required for the page to work. Now the code works on the client-side when the Promise.all resolves it gets both sets of data. However, on the server-side the promises when console.log the promises are both pending and causes Nginx to timeout and give a 504 bad gateway error.
I have tried to get this to work use async/await and promise.all with no avail. see code samples for both below.
Import functions getData and getJsonFile are both using Axios and returning resolved promises with objects of data.
// Using async/await
export default {
async asyncData(context) {
const nameData = await getData('getInformationByNames', {
names: [context.params.name],
referingPage: `https://local.test.com${context.route.fullPath}`
});
const content = await getJsonFile(
`/data/pages/user/${context.params.id}`
);
return {
names: nameData,
content
};
}
}
// Using Promise.all
export default {
async asyncData(context) {
const [nameData, content] = await Promise.all([
getData('getInformationByNames', {
names: [context.params.name],
referingPage: `https://local.test.com${context.route.fullPath}`
}),
getJsonFile(`/data/pages/user/${context.params.id}`)
]);
return {
names: nameData,
content
};
}
}
// getJsonFile
import axios from 'axios';
import replaceStringTokens from '#/scripts/helpers/replaceStringTokens';
export default function getJsonFile(path, redirect = true) {
const jsonFilePath = `${path}.json`;
return axios.get(jsonFilePath).then((response) => {
if (typeof response.data === 'object') {
return replaceStringTokens(response.data);
}
return false;
});
}
// getData
import axios from 'axios';
import getUserDevice from '#/scripts/helpers/getUserDevice';
// require php-serialize node package to serialize the data like PHP would for the api endpoint.
const Serialize = require('php-serialize');
export default function getData(action, data) {
const dataApiAddress = '/api/getData.php';
const dataToPass = data || {};
// all actions available on the api will need to know the users device so add it to the data.
dataToPass.userDevice = getUserDevice();
// package the data like the api expects to receive it
const serializedAndEncodedData = encodeURIComponent(
Serialize.serialize(dataToPass)
);
const axiosParams = {
action,
data: serializedAndEncodedData
};
return axios
.get(dataApiAddress, {
params: axiosParams
})
.then((response) => {
return response.data.data;
})
.catch((error) => {
console.log(error);
return false;
});
}
I would expect that the promises resolve and both sets of data are returned an available for the page to use on both the client and server-side.
Is there a better way to get multiple sets of data or a way to debug the server-side so that I can see what is causing the promises to not resolve on the server?
Fixed the issue the problem was with some discrepancies in the data being queried on the API. The data in the database was using an uppercase letter at the start that must have been input incorrectly. So this was causing the promise to not resolve due to the API sending a query for the lowercase version and in turn causing Nginx to timeout.

fetch the api data and put it inside the tables

I am trying to fetch the api data and put it inside the tables, now i am using mock data
so I was able to write successfully actions and reducers.
now I am able to call the api.
but in the network call I am not see response in the api and seeing blocked response content status.
I am using react hooks for react and redux.
this is where I am making the api call
useEffect(() => {
getPosts(channel);
}, []);
can you tell me how to fix it.
providing my code snippet and sandbox below.
https://codesandbox.io/s/material-demo-kpt5i
demo.js
const channel = useSelector(state => state.channel);
const dispatch = useDispatch();
const getPosts = channel => dispatch(fetchPosts(channel));
useEffect(() => {
getPosts(channel);
}, []);
actions.js
export function fetchPosts(channel) {
return function(dispatch) {
dispatch(requestPosts());
return fetch(`http://jsonplaceholder.typicode.com/users`)
.then(
response => response.json(),
error => console.log("An error occurred.", error)
)
.then(json => {
dispatch(receivedPosts(json));
});
};
}
according to your sample on codesandbox, it is due to you are loading from https site but your source is from http. change http://jsonplaceholder.typicode.com/users to https://jsonplaceholder.typicode.com/users will solve your issue.

How do I call the function with a parameter I set up in firebase functions

I've deployed this code to my firebase functions project:
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
admin.initializeApp()
export const getEmail = functions.https.onRequest((request, response) => {
var from = request.body.sender;
admin.auth().getUserByEmail(from)
.then(snapshot => {
const data = snapshot.toJSON()
response.send(data)
})
.catch(error => {
//Handle error
console.log(error)
response.status(500).send(error)
})
})
Which takes in a email parameter that it gets from the user's input on my app. My app's code looks like this:
Functions.functions().httpsCallable("https://us-central1-projectname.cloudfunctions.net/getEmail").call(email) { (result, error) in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
//email isnt taken
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
print(code, message, details)
}
// ...
}
if let text = (result?.data as? [String: Any])?["text"] as? String {
// email taken
}
}
When I run the app and when that function is called, it seems to do nothing, no error message is shown and no data has been sent back. What am I missing?
Update: I went to the logs and nothing has happened in there as if the function was never called.
You are actually mixing up HTTP Cloud Functions and Callable Cloud Functions:
You Cloud Function code corresponds to an HTTP one but the code in your front-end seems to call a Callable one.
You should adapt one or the other, most probably adapt your Cloud Function to a Callable one, along the following lines:
exports.getEmail = functions.https.onCall((data, context) => {
const from = data.sender;
return admin.auth().getUserByEmail(from)
.then(userRecord => {
const userData = userRecord.toJSON();
return { userData: userData };
})
});
Have a look at the doc for more details, in particular how to handle errors. The doc is quite detailed and very clear.

Unable to use external API on Botpress (axios)

When trying to use axis to query an external Weather API, I get this error
ReferenceError: axios is not defined
at getTropicalCyclones (vm.js:16:9)
Here is my action for getTropicalCyclones {}
(of course I have to hide my client ID and secret)
const getTropicalCyclones = async () => {
const BASE_WEATHER_API = `https://api.aerisapi.com/tropicalcyclones/`
const CLIENT_ID_SECRET = `SECRET`
const BASIN = `currentbasin=wp`
const PLACE = `p=25,115,5,135` // rough coords for PH area of responsibility
const ACTION = `within` // within, closest, search, affects or ''
try {
let text = ''
let response = {}
await axios.get(
`${BASE_WEATHER_API}${ACTION}?${CLIENT_ID_SECRET}&${BASIN}&${PLACE}`
)
.then((resp) => {]
response = resp
text = 'Success retrieving weather!'
})
.catch((error) => {
console.log('!! error', error)
})
const payload = await bp.cms.renderElement(
'builtin_text',
{
text,
},
event.channel
)
await bp.events.replyToEvent(event, payload)
} catch (e) {
// Failed to fetch, this is where ReferenceError: axios is not defined comes from
console.log('!! Error while trying to fetch weather info', e)
const payload = await bp.cms.renderElement(
'builtin_text',
{
text: 'Error while trying to fetch weather info.',
},
event.channel
)
await bp.events.replyToEvent(event, payload)
}
}
return getTropicalCyclones()
So my question is, how do I import axios? I've tried
const axios = require('axios')
or
import axios from 'axios';
but this causes a different error:
Error processing "getTropicalCyclones {}"
Err: An error occurred while executing the action "getTropicalCyclones"
Looking at the package.json on GitHub, it looks like axios is already installed
https://github.com/botpress/botpress/blob/master/package.json
However, I cannot locate this package.json on my bot directory...
Secondly, based on an old version doc it looks like this example code just used axios straight
https://botpress.io/docs/10.31/recipes/apis/
How do I use axios on Botpress?
Any leads would be appreciated
Botpress: v11.0.0
Simply use ES6 import.
include this line at the top of your code.
import axios from 'axios';
Note: I'm expecting that the axios is already installed

Categories

Resources