openapi-generator-cli typescript-axios get only response.data - openapi-generator

I am using openapi-generator-cli typescript-axios for generating client from swagger and generated clients functions returns full request data(header, config, url, etc) but i want only response.data(data that real function returns).
I do not want to wrap client's functions in a new function like wrapperFunction(response => response.data).
Is there any config or anything different to get only response.data?

Sorry if I misunderstood the question.
You can get a portion of object like this
const {data} = axios.get(url)
This way you can retrieve data value of object returned by "axios" request.
You can change name of variable
const {data: myVarName} = axios.get(url)

Related

SvelteKit load function error: must return a plain object at the top level

I cannot get SvelteKit load function works when using it with Firebase, I always get this error message:
a load function related to route '/' returned a function, but must return a plain object at the top level (i.e. return {...})
I'm using onSnapshot here with Firestone to get the updated data whenever it changed on the database.
export function load() {
const queryParams = [orderBy('date')];
const q = query(collection(db, 'daily_status'), ...queryParams);
messagesUnsubscribeCallback = onSnapshot(
q,
querySnapshot => {
let data = querySnapshot.docs.map( doc => (
JSON.parse(JSON.stringify(
{
id: doc.id,
status: doc.data().status,
date: doc.data().date.toDate().toLocaleDateString('en-au'),
note: doc.data().note
}
))
))
return { daily_status: data }
})
return messagesUnsubscribeCallback;
}
It looks like your issue is the fact that you are returning the function onSnapshot() inside the load function. The only thing you can return inside a load method is a plain object as the error states. What you might want to do is to run the snapshot code inside an onMount.
Another solution would be creating a svelte store and pass the onSnapshot into the store. An example can be seen in this tutorial:
https://www.captaincodeman.com/lazy-loading-and-querying-firestore-with-sveltekit#introduction
Reference:
https://kit.svelte.dev/docs/load
Your load() function needs to run asynchronous code, so it can't return back the data directly. Instead, you need to change it to return a promise that resolves to the loaded data. For an example using fetch(), see:
https://kit.svelte.dev/docs/load#making-fetch-requests
In your case, you need to create your own promise.
Further more, the purpose of the load() function is to load the initial data the page needs to be able to render. As suggested by another, to subscribe to updates in the future, do that in the page component in onMount(), so you only subscribe to future updates when the component is rendered in the web browser.

How to make Next-Auth-session-token-dependent server queries with React Query in Next JS?

I am trying to make an API GET request, using React Query's useInfiniteQuery hook, that uses data from a Next Auth session token in the query string.
I have a callback in /api/auth/[...nextauth.ts] to send extra userData to my session token.
There are two relevant pages on the client side. Let's call them /pages/index.tsx and /hooks/useApiData.ts. This is what they look like, for all intents and purposes:
// pages/index.tsx
export default function Page() {
const {data, fetchNextPage, isLoading, isError} = useCourseData()
if (isLoading) return <main />
return <main>
<InfiniteScroller fetchMore={fetchNextPage}>
{data?.pages?.map(page => page?.results?.map(item: string => item))}
</InfiniteScroller>
</main>
}
// hooks/useApiData.ts
async function fetchPage(pageParam: string) {
const response = await fetch(pageParam)
return await response.json()
}
export default function useApiData() {
const {data: session} = useSession()
const init = `/api?userData=${session?.user?.userData}`
return useInfiniteQuery('query',
({pageParam = init}) => fetchPage(pageParam),
{getNextPageParam: prevPage => prevPage.next ?? undefined}
)
}
My initial request gets sent to the API as /api?userData=undefined. The extra data is definitely making its way into the token.
I can place the data from my session in the DOM via the render function of /pages/index.tsx, so I figure the problem is something to do with custom hooks running before the session context is ready, or something like that... I don't understand the mechanics of hooks well enough to figure that out.
I've been looking for answers for a long time, and I'm surprised not to have found a single person with the same issue. These are not unpopular packages and I guess a lot of people are using them in conjunction to achieve what I'm attempting here, so I figure I must be doing something especially dumb. But what?!
How can I get the data from my Next Auth session into my React Query request? And for bonus points, why is the session data not available when the request is sent in my custom hook?

How to call endpoint.select() in RTK query with an argument to retrieve cached data (within another selector)?

I have an endpoint which accepts a parameter and I'm trying to access the cached data using endpoint.select() in a redux slice. The problem is i cant figure out how to pass in the cache key. I've done the following:
export const selectProductsResult = (storeId) =>
storeApi.endpoints.listProductsByStore.select(storeId);
This works fine if I use it within a component like this:
const currentStoreProducts = useSelector(selectProductResult(currentStoreId))
What I don't understand is how I can use this in another selector, for example this does not work:
const selectCurrentProducts = createSelector((selectCurrentStoreId), currentStoreId
=> selectProductResult(currentStoreId)
If I try to use this in a component like so:
const currentProducts = useSelector(selectCurrentProducts)
The value obtained is a memoized function. I've played around quite a bit and can't seem to build the desired selector.
The call to someEndpoint.select() generates a new selector function that is specialized to look up the data for that cache key. Loosely put, imagine it looks like this:
const createEndpointSelector = (cacheKey) => {
return selectorForCacheKey = () => {
return state.api.queries['someEndpointName'][cacheKey];
}
}
const selectDataForPikachu = createEndpointSelector('pikachu');
So, you need to call someEndpoint.select() with the actual cache key itself, and it returns a new selector that knows how to retrieve the data for that cache key:
const selectDataForPikachu = apiSlice.endpoints.getPokemon.select('pikachu');
// later, in a component
const pikachuData = useSelector(selectDataForPikachu);

Dynamic callback endpoints with cloud functions

When a user triggers a function there’s a POST request going away to a partner. Within the body I need to include a unique endpoint callbackURL with an Id so they can send me status updates linked with a specific user. How can I accomplish that? I know how to setup static endpoints, but not create new ones for every request.
As Doug said in his comment above, you don't need a new URL (i.e. a new endpoint) for each different id. You can deploy only one HTTP Cloud Function (which exposes one endpoint) and, in the Cloud Function, you extract the value of id from the Request object with its originalUrl property, as follows:
exports.myWebhook = functions.https.onRequest((req, res) => {
const urlArray = req.originalUrl.split('/');
console.log(urlArray);
console.log(urlArray[1]);
const id = urlArray[1];
//Do whatever you need with id
//.....
//If you want to test that it works with a browser, you can send it back as a response to the browser
res.send(urlArray[1]);
});
You then call this Cloud Function with the following URI:
https://us-central1-yourprojectname.cloudfunctions.net/myWebhook/id/callback
Note that it is also possible to extract values from the Request body, see https://firebase.google.com/docs/functions/http-events?authuser=0#read_values_from_the_request.

Cloud Function Firebase, error sending value back

I'm trying to send back simple value from firebase but error appearing like this
mycode is :
exports.getTotalPrice = functions.https.onRequest((req, res) => {
admin.database().ref('carresult').once('value').then(function(snapshot) {
var totalPrice = snapshot.val().price;
res.status(200).send(totalPrice);
});
});
ps. In error 65000 is the value I need it to send back.
The Express documentation for res.send([body]) indicates:
The body parameter can be a Buffer object, a String, an object, or an
Array
In your database, /carresult/price is likely stored as a number, making totalPrice an invalid parameter to send(). Your options are to store it as a String convert it to a String before passing to send(), or leave it a number and send it back as a property of an object: send({price: totalPrice}).
exports.getTotalPrice = functions.https.onRequest((req, res) => {
admin.database().ref('carresult').once('value').then(function(snapshot) {
var totalPrice = snapshot.val().price;
res.status(200).send(String(totalPrice)); // <= ADDED String()
});
});
Also note that performing a database read (asynchronous) in an HTTPS function is risky, as Frank van Puffelen explains in this answer:
Note that this is a tricky pattern. The call to the database happens
asynchronously and may take some time to complete. While waiting for
that, the HTTP function may time out and be terminated by the Google
Cloud Functions system...As a general rule I'd recommend using a Firebase Database SDK or its REST API to access the database and not rely on a HTTP function as middleware.

Resources