Wednesday, December 9, 2020

Typescript - nodejs 2020 december

api/safeFetch.ts

  • Code:

maximilianou@instrument:~/projects/weekly20$ cat api/safeFetch.ts 


import * as TE from "fp-ts/lib/TaskEither";
import * as E from "fp-ts/lib/Either";
const fetch = require('node-fetch');

type User = {

};

export const safeFetch = (
  url: string,
  errMessage: string
): TE.TaskEither> => 
     TE.tryCatch(
       () => fetch(url).then( res => res.json()),
       () => new Error(errMessage)
     );

safeFetch(
  "https://jsonplaceholder.typicode.com/users",
  "failed to fetch users"
)().then(E.fold(console.error, console.log));

  • Run code, over command line:

maximilianou@instrument:~/projects/weekly20/api$ ./node_modules/.bin/ts-node safeFetch.ts

No comments: