import createRequestBody from './create-request-body' ; import createResponse from './create-response' ; import { format as formatUrl } from './url' ; import { TraeSettings , InstanceConfig } from './types' ; import { merge } from './utils' ; const defaults = { headers : { 'Content-Type' : 'application/json' } } ; function createTrae ( providedConf ? ) { const config = Object . freeze ( merge ( defaults , { before : ( conf ) => conf , onResolve : ( item ) => Promise . resolve ( item ) , onReject : ( err ) => Promise . reject ( err ) , ... providedConf } ) ) ; function request ( endpoint , settings ) { const url = formatUrl ( settings . url , endpoint , settings . params ) ; return fetch ( url , config . before ( settings ) ) . then ( createResponse ( settings ) ) . then ( config . onResolve ) . catch ( config . onReject ) ; } function create ( instanceConfig ) { return createTrae ( merge ( config , instanceConfig ) ) ; } function get ( endpoint , requestConfig ? ) { const settings = merge ( config , requestConfig ) ; return request ( endpoint , { ... settings , method : 'GET' } ) ; } function remove ( endpoint , requestConfig ? ) { const settings = merge ( config , requestConfig ) ; return request ( endpoint , { ... settings , method : 'DELETE' } ) ; } function head ( endpoint , requestConfig ? ) { const settings = merge ( config , requestConfig ) ; return request ( endpoint , { ... settings , method : 'HEAD' } ) ; } function post ( endpoint , body = { } , requestConfig ? ) { const settings = merge ( config , requestConfig ) ; return request ( endpoint , { ... settings , method : 'POST' , body : createRequestBody ( body , settings ) } ) ; } function put ( endpoint , body = { } , requestConfig ? ) { const settings = merge ( config , requestConfig ) ; return request ( endpoint , { ... settings , method : 'PUT' , body : createRequestBody ( body , settings ) } ) ; } function patch ( endpoint , body = { } , requestConfig ? ) { const settings = merge ( config , requestConfig ) ; return request ( endpoint , { ... settings , method : 'PATCH' , body : createRequestBody ( body , settings ) } ) ; } return { create , get , delete : remove , head , post , put , patch , config } ; } export default createTrae ( ) ;