1.0.3 • Published 2 years ago

fx-request v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

fx-request

client http request

  • installation
npm i fx-request

using fetch

// on main app
import Request from 'fx-request';
Request.setMode("fetch"); // default 

using xhr

// on main app
import Request from 'fx-request';
Request.setMode("xhr");

declare a global host for all fetchers

Request.setHost("http://localhost:3001");

inside nodejs server

global.fetch = require("node-fetch");
global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
  • get with querystring and xhr receive 200 json body
        const req = await Request<{name: string}>("/api", { id: 1, name: 'Jhon Doe' }).get()
        expect(req.data.name).toBe('Jhon Doe');
        expect(req.status).toBe(200);
        expect(req.headers.get('content-type')).toBe('application/json; charset=utf-8');
    })
  • post and receive 201 with empty body plain text
        const req = await Request("/api").post({ id: 1, name: 'Jhon Doe' })
        expect(req.data).toBe(undefined);
        expect(req.status).toBe(201);
        expect(req.headers.get('content-type')).toBe('text/plain; charset=utf-8');
    })
  • put and receive 202 with json reponse
        const req = await Request("/api").put({ id: 1 })
        expect(req.status).toBe(202);
        expect(req.data).toBeInstanceOf(Object);
        expect(req.headers.get('content-type')).toBe('application/json; charset=utf-8');
    })
  • delete and receive 401 unauthorized
        try {
            await Request("/api").delete({ id: 1 });

        } catch (error) {
            if(error instanceof Request.Error){
                expect(error.data).toBeInstanceOf(Object);
                expect(error.status).toBe(401);
                expect(error.headers.get('content-type')).toBe('application/json; charset=utf-8');
            }
        }
    })