Support for superjson
digoburigo opened this issue · comments
Describe the feature
Trying to use superjson and it's not working.
const ofetchOptions: FetchOptions = {
baseURL: 'https://jsonplaceholder.typicode.com',
parseResponse: superjson.parse, // this don't work
};
const api = ofetch.create(ofetchOptions);
const data = await api('/todos/1');
console.log(data)
with superjson
data: undefined
Without superjson
data: {
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
}
Additional information
- Would you be willing to help implement this feature?
Would you provide a minimal runnable reproduction so that everyone can see what you see?
https://stackblitz.com/edit/stackblitz-starters-qqq5no?file=index.js
run with node index.js
It seems that you have to superjson.stringify
the response text then pass it to superjson.parse
function.
This is because superjson.parse
function expect a JSON string that has 2 root keys, "json" and "meta", where value of "json" key is the JSON object you want.
superjson.stringify
method accepts a JSON string and internally call superjson.seriarize
to make the JSON have the 2 root keys and then returns the corresponding JSON string, at which point you can superjson.parse
the JSON string.
const ofetchOptions: FetchOptions = {
baseURL: 'https://jsonplaceholder.typicode.com',
parseResponse: (responseText) => superjson.parse(superjson.stringify(responseText))
};
const api = ofetch.create(ofetchOptions);
const data = await api('/todos/1');
console.log(data)
If superjson expects a specific format, API should return the JSON stringified with supervision as a format well to work sensibly.
import { createServer } from 'node:http';
import superjson from 'superjson';
import { ofetch } from 'ofetch';
const server = createServer((req, res) => {
res.end(superjson.stringify({ message: 'Hello World' }));
});
server.listen(3000, async () => {
const res = await ofetch('http://localhost:3000', {
parseResponse: superjson.parse,
});
console.log(res);
});
You might also go further to auto detect the superjson signature by making a wrapper function that checks if string starts with {"json"
to use superjson.parse
and otherwise JSON.parse
as fallback however i think it is something superjson can support for plain json fallback support.