Skip to content

Commit

Permalink
chore: improved typescript example
Browse files Browse the repository at this point in the history
  • Loading branch information
lquixada committed Mar 28, 2021
1 parent f3b2fc4 commit 69b7d5b
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 17 deletions.
54 changes: 39 additions & 15 deletions examples/typescript/index.ts
@@ -1,15 +1,39 @@
import fetch from 'cross-fetch';

fetch('https://api.github.com/users/lquixada')
.then(res => {
if (res.status >= 400) {
throw new Error("Bad response from server");
}
return res.json();
})
.then(user => {
console.log(user);
})
.catch(err => {
console.error(err);
});
/** This is a more complex setup to test type resolutions */
import fetch, { Request, Response, Headers } from 'cross-fetch';

const headers = new Headers({
'Content-Type': 'application/json',
Accept: 'application/json'
})

const customFetch = async (input: RequestInfo, init: RequestInit): Promise<void> => {
const req = new Request(input)

return fetch(req, init)
.then((res: Response): Promise<any> => {
if (res.status >= 400) {
throw new Error("Bad response from server");
}
return res.json();
})
.then((user: any): Promise<Response> => {
// Clone user just for the sake of using `new Response`
const json = JSON.stringify(user);
const res = new Response(json, { headers })

return res.json()
})
.then((user: any): void => {
console.log(user);
})
.catch((err: Error): void => {
console.error(err);
});
};

customFetch('https://api.github.com/users/lquixada', {
method: 'GET',
headers
})


6 changes: 4 additions & 2 deletions examples/typescript/tsconfig.json
Expand Up @@ -4,6 +4,8 @@
"target": "es6",
"module": "commonjs",
"noEmit": true,
"allowSyntheticDefaultImports": true
}
"allowSyntheticDefaultImports": true,
"strict": true
},
"files": ["index.ts"]
}

0 comments on commit 69b7d5b

Please sign in to comment.