Options
All
  • Public
  • Public/Protected
  • All
Menu

Class DataClientPro<D, T>

Data client Pro ( More Customized solution for different api server )

  • Api data structure are not restricted , or some Demo like below :
  • ```json { "count": 30, "next": "http://127.0.0.1:8000/api/assistance/?limit=10&offset=10", "previous": null, "results": [ { "openid": 8, "created": "2020-11-06 16:25", "i1": 12, "no": 1, "modified": "2020-11-06 16:26", "id": "5fa50894b550865b04515e71" } ] }
  • ```
  • First, You shoud know the type of the RawData from server and a single Data item typed , You can use MakeTypes to generate
  • Asume that your rawData type is
    type RawData = {
     count: number
     next?: string
     previous?: string
     results: DataItem[]
    }
  • Asume that the single Data item type is
    type DataItem = {
     openid: number
     created: string
     i1: number
     no: number
     modified: string
     id: string
    }
  • You should specify the parseData method for data parsing , parseData is a parser to handle the return data, for example:
  • parseData method is only worked for getAll to parse the results
    const opts = {
    parseData: (rawData: RawData):DataItem[] => {
      return rawData.results;
    }
    }
  • Then create a new Client
  • Asume the client rest url is : http://url.to/data
  • type D means rawData from response
  • type T means single Data Item for Data list
    import { DataClientPro } from '@21epub/epub-data-client'
    const client = new DataClientPro<RawData , DataItem>('http://url.to/data', opts)
    Create with opts to catch error and error msg by default
    const opts = {
     parseData: (rawData: RawData):DataItem[] => {
        return rawData.results;
     }
     catchError(error){
       if(error.status === 400) message.error(error.response.msg);
     },
     catchMsg(msg){
       message.error(msg)
     }
    }
    const client = new DataClientPro<DataItem>('http://url.to/data', opts)

Type parameters

  • D

  • T: Record<string, any>

Hierarchy

  • DataClientPro

Index

Constructors

constructor

Hooks Properties

useCurrentData

useCurrentData: () => any | undefined

Use current data of data client Current data is an object as below

{
"i1": 12,
"openid": 8,
"id": "5fa50894b550865b04515e71",
"modified": "2020-11-06 16:26",
"created": "2020-11-06 16:25"
}

Type declaration

    • (): any | undefined
    • Returns any | undefined

useCurrentLoading

useCurrentLoading: () => boolean

loading statu hooks for Current Data

Type declaration

    • (): boolean
    • Returns boolean

useData

useData: () => T[]

Hooks of result data Data structure as below:

[
 {
   "openid": 8,
   "created": "2020-11-06 16:25",
   "i1": 12,
   "no": 1,
   "modified": "2020-11-06 16:26",
   "id": "5fa50894b550865b04515e71"
 }
]

Type declaration

    • (): T[]
    • Returns T[]

useDataLoading

useDataLoading: () => boolean

loading statu hooks for Data

Type declaration

    • (): boolean
    • Returns boolean

useQuery

useQuery: () => QueryOpt

Hooks for get query object Can be used with .query() ,async data change

example
const {query} = client.useQuery();  // For example

Type declaration

useRawData

useRawData: () => D | undefined

Hooks of rawData The Demo rawData structure as below:

 {
     "numpages": 1,
     "sum": 1,
     "results": [
       {
         "openid": 8,
         "created": "2020-11-06 16:25",
         "i1": 12,
         "no": 1,
         "modified": "2020-11-06 16:26",
         "id": "5fa50894b550865b04515e71"
       }
     ],
     "facet": [],
     "page": 1,
     "size": 1
 }

And then you can use the data as you wish

example
const Comp = () => {
    const {page, sum ,results } = client.useRawData
}

Type declaration

    • (): D | undefined
    • Returns D | undefined

Other Properties

Protected _current

_current: string | number = ""

Protected _id

_id: string | number = ""

Protected _idAttribute

_idAttribute: string = "id"

Protected _originUrl

_originUrl: string

Origin url of data client , Use with urlReset()

Protected _path

_path: string = ""

Protected _query

_query: QueryOpt

Protected _url

_url: string

Url of data client

Protected Optional catchError

catchError: typeof catchError

Protected Optional catchMsg

catchMsg: undefined | ((msg: string) => void)

Protected currentData

currentData: T | any

Protected currentData$

currentData$: BehaviorSubject<T | undefined> = new BehaviorSubject<T | undefined>(undefined)

currentLoading$

currentLoading$: BehaviorSubject<boolean> = new BehaviorSubject(false)

CurrentData loading rxjs subject Custom trigger on demand Use with fetchCurrent() automatically

Protected data

data: D | T | T[] | undefined

Protected data$

data$: BehaviorSubject<T[]> = new BehaviorSubject<T[]>([])

dataLoading$

dataLoading$: BehaviorSubject<boolean> = new BehaviorSubject(false)

Data loading$ rxjs/BehaviorSubject Custom trigger dataLoading$ state Automatically trigger by getAll()

example
 dataLoading$.next(true);
 ...
 dataLoading$.next(false);

Use with hooks

 const Comp = () => {
   const dataLoading = client.useDataLoading();
   return (
      <>
        {dataLoading? <spin/> : <Table/>}
      </>
   )
 }

Optional parseData

parseData: ProParseDataFC<D, T>

Parse data of data client pro parseData only for getAll to parse the server data Initialize it from contructor function

example
parseData : (rawData? : RawData) => rawData.results

Protected query$

query$: BehaviorSubject<QueryOpt> = new BehaviorSubject<QueryOpt>({})

Protected rawData

rawData: D | undefined

Protected rawData$

rawData$: BehaviorSubject<D | undefined> = new BehaviorSubject<D | undefined>(undefined)

Chain Operators Methods

id

  • id(idString: string | number): this
  • id prefix for Request (exclude getAll) always use with request functions

    example
     const result = await client.id('12345').patch({title: '标题'});

    Parameters

    • idString: string | number

    Returns this

options

path

  • Set path suffix for all request Path will be cleared after usage

    example
     await DataClientPro.id('12345').path('publish/').post();

    Parameters

    • p: string

    Returns DataClientPro<D, T>

query

url

  • url(u: string): this
  • Change client main url Can reset by this.urlReset()

    Parameters

    • u: string

    Returns this

urlReset

  • urlReset(): this

Get Local Data Or Settings Methods

getCurrent

  • getCurrent(): string | number

getCurrentData

  • getCurrentData(): any

getData

  • getData(): undefined | D | T | T[]

getOptions

getQuery

getRawData

  • getRawData(): undefined | D

getUrl

  • getUrl(): string

Local Data Modification Methods

appendLocal

  • appendLocal(body: T): undefined | D | T | T[]
  • Append a single data to the end of the local data list Without any sync with server

    Parameters

    • body: T

    Returns undefined | D | T | T[]

deleteLocal

  • deleteLocal(): undefined | D | T | T[]
  • Delete a single Data from local

    example

    Delete a dataobject of id === '12345'

     client.id('12345').deleteLocal();

    Returns undefined | D | T | T[]

patchLocal

  • patchLocal(body?: Partial<T>): void
  • Patch a local data object value without sync server request

    Parameters

    • Default value body: Partial<T> = {}

    Returns void

prependLocal

  • prependLocal(body: T): undefined | D | T | T[]

putLocal

  • putLocal(body?: Partial<T>): void

updateLocal

  • updateLocal(data: T[]): undefined | D | T | T[]
  • Update all data locally !Caution: This function only changes the data list without modify the 'sum' value

    Parameters

    • data: T[]

    Returns undefined | D | T | T[]

updateRawDataLocal

  • updateRawDataLocal(rawData: D): undefined | D

Other Methods

Protected clearIdPath

  • clearIdPath(): void

current

  • current(id: string | number): this
  • change current Use it with fetchCurrent to fetch current item's data from server Or use fetchCurrentLocal from this.data Id params will be cleared after using.

    Parameters

    • id: string | number

    Returns this

Protected emit$

  • emit$(): void

fetchCurrentLocal

  • fetchCurrentLocal(): T | undefined
  • fetch current data from this.data

    example
     client.current('12345').fetchCurrentLocal();

    Returns T | undefined

rawAjax

  • A low level request use as what you want . It return a rxjs/ajax observer

    Parameters

    • url: string
    • method: Method
    • Optional body: AjaxRequest["body"]

    Returns Observable<AjaxResponsePro<D>>

    rxjs/ajax observer

rawRequest

  • rawRequest(url: string, method: Method, body?: AjaxRequest["body"]): Promise<void | T[] | D | T | any>
  • A low level request function . Returns a request Promise It will not preserve the return data

    Parameters

    • url: string
    • method: Method
    • Optional body: AjaxRequest["body"]

    Returns Promise<void | T[] | D | T | any>

Request Functions Methods

delete

  • delete(body?: AjaxRequest["body"]): Promise<any>
  • example
    await client.id('12345').delete();

    Parameters

    • Optional body: AjaxRequest["body"]

    Returns Promise<any>

fetchCurrent

  • fetchCurrent(): Promise<any>
  • fetch Current Item data from server Allowed path suffix automately preserve data to this._currentData useCurrentData will affected by update !Caution: parseData will not Effect this method !Caution: Not like DataClient , Because the dataStructure maybe different , So data list may not be updated only if the return data fit the structure of a single item

    example
    await client.path('object').fetchCurrent()   // will fetch from url http://url/id/object

    Returns Promise<any>

get

  • get(): Promise<any>
  • use to get a single data or other usage will not preserve the data

    await client.id('12345').get()    // get object by id '12345'

    Current Catch after request

    await client.id('12345').get().catch(err => console.log(error.response.msg))

    Returns Promise<any>

getAll

  • getAll(): Promise<undefined | D | T | T[]>
  • fetch All context datas preserve the data to this.rawData and this.data Every fetch success for change the data

    await client.getAll()  // will fetch from http://url
    await client.getAll().catch(err=> console.log(err))  // fetch for custom error catch

    You can also change url temporary or make path suffix to the url, id() not support

    await client.url('http://newurl").getAll()  // fetch from url `http://newurl`
    await client.path('all/').getAll()    // fetch from url  `http://url/all/`

    getAll() with page , size and query arguments

     await client.page(2).size(20).query({query:"demo"}).getAll() ;

    Result will be prased by parseData

    Returns Promise<undefined | D | T | T[]>

option

  • option(body?: AjaxRequest["body"]): Promise<any>

patch

  • patch(body?: AjaxRequest["body"]): Promise<any>
  • Patch partial data to server

    Parameters

    • Optional body: AjaxRequest["body"]

    Returns Promise<any>

post

  • post(body?: AjaxRequest["body"]): Promise<any>
  • restful api to post a new object

    example
    const result = await client.post({
     "openid": 8,
     "created": "2020-11-06 16:25",
     "i1": 12,
     "no": 1,
     "modified": "2020-11-06 16:26"
    });

    Parameters

    • Optional body: AjaxRequest["body"]

    Returns Promise<any>

put

  • put(body?: AjaxRequest["body"]): Promise<any>
  • Rest api to put

    example
    const result = await client.id('5fa50894b550865b04515e71').put( {
        "openid": 8,
        "created": "2020-11-06 16:25",
        "i1": 12,
        "no": 1,
        "modified": "2020-11-06 16:26",
         "id": "5fa50894b550865b04515e71"
      })

    Parameters

    • Optional body: AjaxRequest["body"]

    Returns Promise<any>

Object literals

Protected _options

_options: object

_options of data client TODO: acceptMethods: methods to accept in request contentType: You can change de mode for request addBackSlash: If the url will end with a backSlash

acceptMethods

acceptMethods: ("POST" | "GET" | "PUT" | "DELETE" | "OPTION" | "PATCH")[] = ['POST', 'GET', 'PUT', 'PATCH', 'OPTION', 'DELETE']

addBackSlash

addBackSlash: false = false

ajaxRequestOptions

ajaxRequestOptions: {}

Type declaration

contentType

contentType: "application/json" = "application/json"

idAttribute

idAttribute: string = "id"

Generated using TypeDoc