Skip to content

Commit

Permalink
Create axios instance for any model
Browse files Browse the repository at this point in the history
  • Loading branch information
ruddenchaux committed Jul 15, 2018
1 parent 652ca58 commit 149be68
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 157 deletions.
98 changes: 60 additions & 38 deletions src/http/Http.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,47 @@
import Axios, { AxiosRequestConfig, AxiosPromise, AxiosResponse } from 'axios'
import Axios, {
AxiosRequestConfig,
AxiosPromise,
AxiosResponse,
AxiosInstance
} from 'axios'

export type InterceptorRequestClosure =
(record: AxiosRequestConfig) => AxiosRequestConfig | Promise<AxiosRequestConfig>

export type InterceptorResponseClosure =
(record: AxiosResponse) => AxiosResponse<any> | Promise<AxiosResponse<any>>

export interface InterceptosClosures {
requestInterceptors?: InterceptorRequestClosure[];
responseInterceptors?: InterceptorResponseClosure[]
}

export type HttpConf = AxiosRequestConfig;

export default class Http {
private axiosInstance: AxiosInstance

constructor(
config: AxiosRequestConfig & InterceptosClosures,
defaultConfig: AxiosRequestConfig & InterceptosClosures
) {
this.axiosInstance = Axios.create(this.mergeConf(config, defaultConfig));

if(config.requestInterceptors && Array.isArray(config.requestInterceptors)) {
config.requestInterceptors.forEach(
(value: InterceptorRequestClosure) => {
this.axiosInstance.interceptors.request.use(value)
}
)
}

public static defaultConf: AxiosRequestConfig

public static conf(config: AxiosRequestConfig) {
this.defaultConf = config
if(config.responseInterceptors && Array.isArray(config.responseInterceptors)) {
config.responseInterceptors.forEach(
(value: InterceptorResponseClosure) => {
this.axiosInstance.interceptors.response.use(value)
}
)
}
}

public static registerRequestInterceptor(requestInterceptor: InterceptorRequestClosure) {
Expand All @@ -24,58 +52,52 @@ export default class Http {
Axios.interceptors.response.use(responseInterceptor)
}

private static mergeConf(config: AxiosRequestConfig) {
return { ...this.defaultConf, ...config }
private mergeConf(config: AxiosRequestConfig, defaultConfig: AxiosRequestConfig) {
return { ...defaultConfig, ...config }
}

public static head (
public head (
url: string,
config: AxiosRequestConfig = this.defaultConf
config?: AxiosRequestConfig
): AxiosPromise<any> {
this.mergeConf(config)
return Axios.head(url, config);
return this.axiosInstance.head(url, config);
}

public static get <T> (
public get <T> (
url: string,
config: AxiosRequestConfig = this.defaultConf
config?: AxiosRequestConfig
): AxiosPromise<T> {
this.mergeConf(config)
return Axios.get<T>(url, config);
return this.axiosInstance.get<T>(url, config);
}

public static post <T> (
url: string,
data = {},
config: AxiosRequestConfig = this.defaultConf
public post <T> (
url: string,
data = {},
config?: AxiosRequestConfig
): AxiosPromise<T> {
this.mergeConf(config)
return Axios.post<T>(url, data, config);
return this.axiosInstance.post<T>(url, data, config);
}

public static patch <T> (
url: string,
data = {},
config: AxiosRequestConfig = this.defaultConf
public patch <T> (
url: string,
data = {},
config?: AxiosRequestConfig
): AxiosPromise<T> {
this.mergeConf(config)
return Axios.patch<T>(url, data, config);
return this.axiosInstance.patch<T>(url, data, config);
}

public static put <T> (
url: string,
data = {},
config: AxiosRequestConfig = this.defaultConf
public put <T> (
url: string,
data = {},
config?: AxiosRequestConfig
): AxiosPromise<T> {
this.mergeConf(config)
return Axios.put<T>(url, data, config);
return this.axiosInstance.put<T>(url, data, config);
}

public static delete (
url: string,
config: AxiosRequestConfig = this.defaultConf
public delete (
url: string,
config?: AxiosRequestConfig
): AxiosPromise<any> {
this.mergeConf(config)
return Axios.delete(url, config);
return this.axiosInstance.delete(url, config);
}
}
74 changes: 43 additions & 31 deletions src/model/Model.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import BaseModel from './BaseModel'
import Http, { HttpConf }from '../http/Http'
import Http from '../http/Http'
import { Record } from '../data'
import Query, { UpdateClosure } from '../query/Query'
import EntityCollection from '../query/EntityCollection'
import { Collection, Item } from '../query'
import ModelConf, {
JsonModelConf,
defaultConf,
MethodConf,
defaultConf,
PathParam
} from '../model/ModelConf'
import ModuleOptions from '../options/Options'
import { replaceAll } from '../support/Utils'

export type UpdateReturn = Item | Collection | EntityCollection
export type MethodConfParameter = MethodConf & HttpConf

export default class Model extends BaseModel {
public static _conf: ModelConf | (JsonModelConf & HttpConf)
private static _conf: ModelConf | JsonModelConf
private static _http: Http

/**
* Configure a model with default conf and extend or override
Expand All @@ -29,7 +30,7 @@ export default class Model extends BaseModel {
*/
public static conf (parameterConf?: JsonModelConf): void {

const _onModelconf: JsonModelConf = this._conf as JsonModelConf
const _onModelconf = this._conf as JsonModelConf

// instance default conf
this._conf = new ModelConf(
Expand Down Expand Up @@ -67,6 +68,8 @@ export default class Model extends BaseModel {
)
)
}

this._http = new Http(this._conf.http, ModuleOptions.getDefaultHttpConfig());
}

/**
Expand All @@ -76,15 +79,17 @@ export default class Model extends BaseModel {
* @async
* @return {Promise<UpdateReturn>} fetched data
*/
public static async fetch (conf: MethodConfParameter = this.getMethodConf('fetch')): Promise<Collection> {
public static async fetch (
conf: MethodConf = this.getMethodConf('fetch')
): Promise<Collection> {
const _conf = this.checkMethodConf('fetch', conf)
const url = this.getUrl(_conf)
/* const data = await Http[((_conf.http as any) as any).method as HttpMethod](url)
/* const data = await this._this._http[((_conf.http as any) as any).method as HttpMethod](url)
.catch((err: Error) => { console.log(err) }) || [] */

const method = (_conf.http as any).method as string
const data = await Http[method](url)
.catch((err: Error) => { console.log(err) }) || []
const data = await this._http[method](url, _conf.http)
.catch((err: Error) => { console.log(err) }) || []

if (_conf.localSync) {
await this.dispatch('insertOrUpdate', { data })
Expand All @@ -99,7 +104,7 @@ export default class Model extends BaseModel {
* @async
* @return {Promise<Collection>} list of results
*/
public static async find (conf: MethodConfParameter = this.getMethodConf('find')): Promise<Collection> {
public static async find (conf: MethodConf = this.getMethodConf('find')): Promise<Collection> {
const _conf = this.checkMethodConf('find', conf)
let data
if (_conf.remote) {
Expand All @@ -122,7 +127,7 @@ export default class Model extends BaseModel {
*/
public static async findById (
id: number,
conf: MethodConfParameter = this.getMethodConf('findById')
conf: MethodConf = this.getMethodConf('findById')
): Promise<Item> {
const _conf = this.checkMethodConf('findById', conf)
let data
Expand All @@ -148,12 +153,12 @@ export default class Model extends BaseModel {
*/
public static async fetchById (
id: number,
conf: MethodConfParameter = this.getMethodConf('fetchById')
conf: MethodConf = this.getMethodConf('fetchById')
): Promise<Item> {
const _conf = this.checkMethodConf('fetchById', conf)
const url = this.getUrl(_conf, new PathParam('id', id.toString()))
const method = (_conf.http as any).method as string
const data = await Http[method](url)
const data = await this._http[method](url, _conf.http)
.catch((err: Error) => { console.log(err); }) || []

if(_conf.localSync) {
Expand All @@ -172,15 +177,15 @@ export default class Model extends BaseModel {
*/
public static async exist (
id: number,
conf: MethodConfParameter = this.getMethodConf('exist')
conf: MethodConf = this.getMethodConf('exist')
): Promise<boolean> {
const _conf = this.checkMethodConf('exist', conf)
let data

if (_conf.remote) {
const url = this.getUrl(_conf, new PathParam('id', id.toString()))
const method = (_conf.http as any).method as string
data = await Http[method](url)
data = await this._http[method](url, _conf.http)
.catch((err: Error) => { console.log(err); }) || []
}
else {
Expand All @@ -195,13 +200,13 @@ export default class Model extends BaseModel {
* @static
* @return {Promise<Number>} number of element
*/
public static async count (conf: MethodConfParameter = this.getMethodConf('count')): Promise<number> {
public static async count (conf: MethodConf = this.getMethodConf('count')): Promise<number> {
const _conf = this.checkMethodConf('count', conf)
let data

if (_conf.remote) {
const method = (_conf.http as any).method as string
data = await Http[method](this.getUrl(_conf))
data = await this._http[method](this.getUrl(_conf), _conf.http)
.catch((err: Error) => { console.log(err); }) || []
}
else {
Expand All @@ -219,14 +224,14 @@ export default class Model extends BaseModel {
*/
public static async create (
data: Record | Record[],
conf: MethodConfParameter = this.getMethodConf('create')
conf: MethodConf = this.getMethodConf('create')
): Promise<EntityCollection> {

const _conf = this.checkMethodConf('create', conf)
let dataOutput
if (_conf.remote) {
const method = (_conf.http as any).method as string
dataOutput = await Http[method](this.getUrl(_conf), data)
dataOutput = await this._http[method](this.getUrl(_conf), data, _conf.http)
.catch((err: Error) => { console.log(err); }) || []

if(_conf.localSync) {
Expand All @@ -252,15 +257,15 @@ export default class Model extends BaseModel {
public static async update (
id: number,
data: Record | Record[] | UpdateClosure,
conf: MethodConfParameter = this.getMethodConf('update')
conf: MethodConf = this.getMethodConf('update')
): Promise<UpdateReturn> {

const _conf = this.checkMethodConf('update', conf)
let dataOutput
if (_conf.remote) {
const url = this.getUrl(_conf, new PathParam('id', id.toString()))
const method = (_conf.http as any).method as string
dataOutput = await Http[method](url, data)
dataOutput = await this._http[method](url, data, _conf.http)
.catch((err: Error) => { console.log(err); }) || []

if(_conf.localSync && dataOutput) {
Expand Down Expand Up @@ -289,15 +294,15 @@ export default class Model extends BaseModel {
*/
public static async deleteById (
id: number,
conf: MethodConfParameter = this.getMethodConf('deleteById')
conf: MethodConf = this.getMethodConf('deleteById')
): Promise<void> {

const _conf = this.checkMethodConf('deleteById', conf)

if (_conf.remote) {
const url = this.getUrl(_conf, new PathParam('id', id.toString()))
const method = (_conf.http as any).method as string
const dataOutput = await Http[method](url)
const dataOutput = await this._http[method](url, _conf.http)
.catch((err: Error) => { console.log(err); }) || []

if(_conf.localSync && dataOutput) {
Expand All @@ -315,13 +320,14 @@ export default class Model extends BaseModel {
* @param {MethodConf} conf a method's conf
* @static
*/
public static async delete (conf: MethodConfParameter = this.getMethodConf('deleteById')): Promise<void> {
public static async delete (
conf: MethodConf = this.getMethodConf('deleteById')): Promise<void> {

const _conf = this.checkMethodConf('deleteById', conf)

if (_conf.remote) {
const method = (_conf.http as any).method as string
const dataOutput = await Http[method](this.getUrl(_conf))
const dataOutput = await this._http[method](this.getUrl(_conf))
.catch((err: Error) => { console.log(err); }) || []

if(_conf.localSync && dataOutput) {
Expand Down Expand Up @@ -350,11 +356,14 @@ export default class Model extends BaseModel {
* @static
* @return {string} api's url
*/
protected static getUrl (conf: MethodConfParameter, ...pathParams: PathParam[]): string {
protected static getUrl (
conf: MethodConf,
...pathParams: PathParam[]
): string {
const methodPath = pathParams.length ?
(conf.http as any).bindPathParams(pathParams) : (conf.http as any).path
conf.bindPathParams(pathParams) : (conf.http as any).url

return this._conf.endpointPath + methodPath
return this._conf.http!.url + methodPath
}

/**
Expand All @@ -368,7 +377,10 @@ export default class Model extends BaseModel {
* @return {MethodConf} the new method's configuration
* @throws Error
*/
protected static checkMethodConf (methodName: string, conf: MethodConfParameter): MethodConf {
protected static checkMethodConf (
methodName: string,
conf: MethodConf
): MethodConf {
const _conf = this._conf as ModelConf
let _method = _conf.method(methodName)
if (conf && _method) {
Expand Down Expand Up @@ -396,7 +408,7 @@ export default class Model extends BaseModel {
* @static
* @return {MethodConf}
*/
protected static getMethodConf (methodName: string): MethodConfParameter {
return this.getConf().method(methodName) as MethodConfParameter
protected static getMethodConf (methodName: string): MethodConf {
return this.getConf().method(methodName) as MethodConf
}
}
Loading

0 comments on commit 149be68

Please sign in to comment.