Giter VIP home page Giter VIP logo

core's Introduction

apicase-core

A 2 KB library to organize your APIs in a smart way.

Introduction

There are so many questions about how to properly organize and work with APIs in frontend applications.

Some people just don't think about it much; they use native fetch, but it's not very flexible or extensible. Some people create their own wrappers (classes, functions, or json objects), but those often become unusable in other projects because they were made for specific APIs.

There's another problem—the API is often not separated from the application into an isolated layer. It means that you can't reuse your APIs with different projects or frameworks.

Here is apicase—a unified way to create that isolated API layer.

General features

  • events-based requests handling
  • middlewares to update/change-on-fly/undo/redo API calls
  • adapters instead of concrete tools (fetch/xhr)
  • services with unlimited inheritance

Browser supports & restrictions

Library sources are transpiled with babel-preset-env but we don't add polyfills to our library to save its size and avoid code duplicates if your project already has polyfills.
So here's the list of features you need to know:

  • You have to add Promises polyfill or use babel-polyfill to work with IE 11 [caniuse]
  • Fetch is used in @apicase/adapter-fetch. You might need fetch polyfill to work with IE 11 or you can just use @apicase/adapter-xhr [caniuse]
  • AbortController is used in @apicase/adapter-fetch to implement req.cancel() and hasn't polyfills. Apicase will work well if AbortController is not supported but note that request just won't be really cancelled [caniuse]

Documentation

Full docs

Read on GitHub pages

Basic request

Wrap adapter into apicase method and use it like it's Axios

import { apicase } from '@apicase/core'
import fetch from '@apicase/adapter-fetch'

const doRequest = apicase(fetch)

const { success, result } = await doRequest({
  url: '/api/posts/:id',
  method: 'POST',
  params: { id: 1 },
  body: {
    title: 'Hello',
    text: 'This is Apicase'
  },
  headers: {
    token: localStorage.getItem('token')
  }
})

if (success) {
  console.log('Yay!', result)
} else {
  console.log('Hey...', result)
}

Events-based requests handling

Following "Business logic failures are not exceptions" principle,
Apicase separates error handling from request fails:

doRequest({ url: "/api/posts" })
  .on("done", res => {
    console.log("Done", res)
  })
  .on("fail", res => {
    console.log("Fail", res)
  })
  .on("error", err => {
    console.error(err)
  })

Apicase services

Move your API logic outside the main application code
Check out @apicase/services repository and docs page for more info

import fetch from "@apicase/adapter-fetch"
import { ApiService } from "@apicase/services"

const ApiRoot = new ApiService({
  adapter: fetch,
  url: "/api"
})
  .on("done", logSucccess)
  .on("fail", logFailure)

const AuthService = ApiRoot.extend({ url: "auth" }).on("done", res => {
  localStorage.setItem("token", res.body.token)
})

AuthService.doRequest({
  body: { login: "Apicase", password: "*****" }
})

Request queues

Keep correct order of requests using queues
Check out docs page for more info

import { ApiQueue } from "@apicase/core"

const queue = new ApiQueue()

queue.push(SendMessage.doRequest, { body: { message: "that stuff" } })
queue.push(SendMessage.doRequest, { body: { message: "really" } })
queue.push(SendMessage.doRequest, { body: { message: "works" } })

TODO

  • Add plugins support to make work much easier
  • Create apicase-devtools

Author

Anton Kosykh

License

MIT

core's People

Contributors

andreaminato avatar beraliv avatar frizar avatar kelin2025 avatar ninjaparade avatar timkindberg avatar vasyukov-nz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

core's Issues

Fetch adapter and JSON body

Fetch adapter sends body "as is" so here is a problem with json - it needs to be prepared by JSON.stringify

[Question] Fetch vs XHR adapter

Since both adapter adhere to the same contract, is there any reason to use the fetch adapter over the XHR adapter?

Thanks!

start Event not firing

Hey,

I want to show a loading indicator so I want to use the start event to set a loading boolean.
However the start event is not firing, the finish event is firing.

doRequest(payload)
    .on("start", () => {
        console.log('loading true');
    })
    .on("finish", () => {
        console.log('loading false');
    });

I am using ApiService and the fetch adapter.

TimeOut request

How do I set a timeout for a request?

As I read in the docs i should accomplish that setting the timeout option like this

const rootService = new ApiService({
  adapter: fetch,
  mode: "cors",
  options: { timeout: 20000 },
  hooks: {
    before({ payload, meta, next }) {
      if (meta.guest) return next(payload);
      else {
        const token = store.state.auth.token;
        next(withToken(token, payload));
      }
    }
  }
});
rootService.on("fail", e => {
  if (e.status === 403) {
    store.dispatch("auth/unauthorized", e.body);
  }
  console.log({ status: "fail", obj: e });
});
rootService.on("error", e => {
  store.dispatch("handleAppError", e.body);
  console.log({ status: "error", obj: e });
});

But doing like this I end up with this error

[Apicase.deprecated] Delayed requests and features of Requests+ are now deprecated. Use https://github.com/apicase/spawner instead apicase.js:141:6
------
TypeError: 'abort' called on an object that does not implement interface AbortController.[Ulteriori informazioni] apicase.js:205:31
    cancel apicase.js:205:31
    start/< apicase.js:197:29

So i believe that I shoul use the spawner but I can't find in the docs how to set a timeout with the spawner, also i don't have the time to rewrite all the infrastructure using spawners just to set a timeout in the base service

As here it seems to be a todo. What may I do?

Refactor request flow

Now it spawns promises that cannot be .catch() ed. Need to fix and create one queue

CORS Support?

Is it possible to call the api from external server? I got the same origin error when trying external url.

Request mode is "same-origin" but the URL's origin is not same as the request origin

Improve docs

Todo:

  • Split docs to several pages
  • Add lifecycle diagram
  • Make docs site (?)

Success / error hook breaks down promise result

Hooks breaks down promise resolve/reject result because resolve/reject callbacks follow the success/error hooks in pipeM and gets nothing

Apicase.call({ 
    url: '/api/posts',
    hooks: {
        success (data, next) {
            console.log(data)  // logs data
            next()
        }
    }
}).then(console.log) // logs undefined

Refactoring: hooks

Today's hooks realisation is hardcoded and needs to be rewritten.

NOTE: It won't cause API changes, only refactoring

Хук done() не модифицирует result

const ApiRoot = new ApiService(fetch, {
  url: `${config.url}:${config.apiPort}/api`,
  hooks: {
    done({ next, result, meta: { onlyBody } }) {
      const data = onlyBody ? result.body : result;
      next(data);
    },
  },
  meta: { onlyBody: true },
});

const TagsService = ApiRoot.extend();

const getTags = () => {
  return TagsService.doRequest({
    url: 'tags',
    method: 'GET',
  }).then(newResult => {
    // newResult выводит результат, который был до вызова хука
    console.log('newResult', newResult);
  });
};

const not supported in strict mode

Heya,

I'm building a project with nuxt/vue and apicase. However I run into an issue with iOS Safari Version 9:

Unexpected keyword 'const'. Const declarations are not supported in strict mode.(anonymous function) @ vendors.app.js:12
Line 12:
const fetch =

I already tried with transpileDependencies: ["@apicase/adapter-fetch"], but no chance.

Seems the issue could have something todo with #25

Supported browsers in readme

It would be nice if you include some informations about supported browsers or required polyfills into the readme.
At least i was not able to find this information.

Need help for supporting IE11 with vue

Hi i'm trying to replace my api layer done with axios to use apicase on a project that is going to be quite big.
It all works like a charm on chrome/firefox/edge and safari but i have some problem with IE.

I have read the documentationon your readme but i can't figure out how to make it work on IE.

I'm using vueJs (vue cli 3.0.1) as the frontend framework and they have a dedicated page in their documentation here.

I have tried all 3 the options provided by the vue team and I event tried to link the script tag in the index file but Ie alway come up with this error (promises and fetch)

SCRIPT1002: Syntax error
app.js (812,23)

/***/ "./node_modules/@apicase/adapter-fetch/index.js":
/*!******************************************************!*\
  !*** ./node_modules/@apicase/adapter-fetch/index.js ***!
  \******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
const fetch =
  (typeof window === 'object' && window.fetch) || __webpack_require__(/*! node-fetch */ "./node_modules/node-fetch/browser.js")
const pathToRegexp = __webpack_require__(/*! path-to-regexp */ "./node_modules/@apicase/adapter-fetch/node_modules/path-to-regexp/index.js")

var _FormData = typeof FormData !== 'undefined' ? FormData : function() {}

const parseUrl = url => { /// <--- HERE IS THE ERROR
  let origin = ''
  let pathname = ''
  if (url.indexOf('://') > -1) {
    const res = url.match('(^(?:(?:.*?)?//)?[^/?#;]*)(.*)')
    origin = res[1]
    pathname = res[2]
  } else {
    pathname = url
  }
  return { origin, pathname }
}

const compilePath = (url, params) => pathToRegexp.compile(url)(params)


//other code from the lib

As i can see it seems that it fails with an arrow function.

What could I be wrong?

When using `doUniqueRequest` the url is being duplicated (concatenated).

Description

When using doUniqueRequest with ApiService the url is being duplicated.
Using doRequest works fine.

"@apicase/adapter-fetch": "^0.15.1",
"@apicase/core": "^0.17.2",
"@apicase/services": "^0.8.2"

Reproduce

BaseService.js

/*
* Base service setting cors, fetch adapter and base url of the api 
*/
export const SimpleBaseService = new ApiService({
  adapter: fetch,
  url: "http://localhost:8080/api",
  mode: 'cors'
});

UserService.js

/*
* Just a simple hook to log the payload before each request. 
*/
const beforeLoggingRequest = ({ payload, next }) => {
  console.log("Before User Service Call");
  console.log(payload);
  next(payload);
};

/*
* Extending the base service and setting up the before hook.
*/
const UserService =  SimpleBaseService.extend({
  hooks: {
    before: beforeLoggingRequest
  }
});

Then when using with doUniqueRequest the url is being duplicated:

const { success, result } = await UserService.doUniqueRequest({
    method: "GET"
  });

This call logs:

> Before User Service Call
> {url: "http://localhost:8080/api/http://localhost:8080/api", mode: "cors", method: "GET"}
method: "GET"
mode: "cors"
url: "http://localhost:8080/portalcesa/http://localhost:8080/portalcesa"

It also throws this exception (screenshot): http://prntscr.com/p5feym

Service.use()

Idea

Idea is to introduce "plugins"

export const authPlugin = service => {
  return service.extend({
    hooks: {
      before ({ payload, next }) {
        payload.headers = { 
          ...(payload.headers || {}),
          Authorization: localStorage.getItem('token')
        }
      }
    }
}

Then we can do that:

import { ApiService } from '@apicase/core'
import fetch from '@apicase/adapter-fetch'
import authPlugin from '@apicase/plugin-auth'

const Service = new ApiService(fetch).use(authPlugin)

Complete tests

We need to update tests to actual state and write the missing

Create apicase-services

It will be here

  • Invokes Apicase.of for every nested options object
  • Support creating services tree from children instances (with Apicase.extend and Apicase.or)

Approximate view of my idea
image

Payload ignore all properties except url

I just use basic example with simple changes:

import { apicase } from '@apicase/core'
import fetch from '@apicase/adapter-fetch'

const doFetchRequest = apicase(fetch)

doFetchRequest({
  url: 'http://localhost:3000/users',
  method: 'POST',
  headers: { token: 'my_secret_token_123' },
  body: {
    some: 'data'
  }
 });

Expected result: POST request with data from body prop and token in headers
Real result: GET request with no body and no token in request headers.

I really enjoy how great this library, but it doesnt work properly for me :(
P.S. Axios works fine...

Sorry for my english.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.