Options
All
  • Public
  • Public/Protected
  • All
Menu

Class DataClient<T>

Data client

  • Causion First: Every api using this module should fit the response data structure as below
  • ```json { "msg": "success", "code": 200, "data": { "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 } }
  • ```
  • First, You shoud know the type of a single Data item typed , You can use MakeTypes to generate
  • Asume that the single Data item type is
    type DataItem = {
     openid: number
     created: string
     i1: number
     no: number
     modified: string
     id: string
    }
  • Then create a new Client
  • Asume the client rest url is : http://url.to/data
    import { DataClient } from '@21epub/epub-data-client'
    const client = new DataClient<DataItem>('http://url.to/data')
    Create with opts to catch error and error msg by default
    const opts = {
     catchError(error){
       if(error.status === 400) message.error(error.response.msg);
     },
     catchMsg(msg){
       message.error(msg)
     }
    }
    const client = new DataClient<DataItem>('http://url.to/data', opts)

Type parameters

  • T: Record<string, any>

Hierarchy

  • DataClient

Index

Constructors

constructor

Hooks Properties

useCurrentData

useCurrentData: () => T | 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

    • (): T | undefined
    • Returns T | 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: () => Data<T>

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
 }
example
const Comp = () => {
    const {page, sum ,results } = client.useRawData
}

Type declaration

Other Properties

Protected _current

_current: string | number = ""

Protected _id

_id: string | number = ""

Protected _idAttribute

_idAttribute: string = "id"

Protected _numpages

_numpages: number = 1

Protected _originUrl

_originUrl: string

Origin url of data client , Use with urlReset()

Protected _page

_page: number = 1

Protected _path

_path: string = ""

Protected _query

_query: QueryOpt

Protected _size

_size: number | undefined = undefined

Protected _sum

_sum: number = 0

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: T[] = []

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/>}
      </>
   )
 }

Protected query$

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

Protected rawData

rawData: Data<T>

Protected rawData$

rawData$: BehaviorSubject<Data<T>> = new BehaviorSubject<Data<T>>(generateInitData())

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

page

  • Set page for getAll() only

    • Notice: This is a Operator only for getAll method , other method not care *
    example
     await dataClient.page(2).getAll();

    Parameters

    • Default value p: number = 1

    Returns DataClient<T>

path

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

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

    Parameters

    • p: string

    Returns DataClient<T>

query

  • Set the query args only for getAll function

    • Notice: This is a Operator only for getAll method , other method not care *

    Parameters

    • Default value q: {} = {}

    Returns DataClient<T>

size

  • size(s?: number): this
  • Set size only for getAll()

    • Notice: This is a Operator only for getAll method , other method not care *
    example
     await dataClient.page(3).size(20).getAll();

    Parameters

    • Default value s: number = 10

      size / per page to fetch data

    Returns this

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(): T[]

getOptions

getPage

  • getPage(): number

getQuery

getRawData

  • getRawData(): Data<T>

getSize

  • getSize(): undefined | number

getUrl

  • getUrl(): string

Local Data Modification Methods

appendLocal

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

    Parameters

    • body: T

    Returns T[]

deleteLocal

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

    example

    Delete a dataobject of id === '12345'

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

    Returns 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): T[]

putLocal

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

updateLocal

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

    Parameters

    • data: T[]

    Returns T[]

updateRawDataLocal

  • updateRawDataLocal(rawData: Data<T>): Data<T>

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<AjaxFetcherResponse<T>>

    rxjs/ajax observer

rawRequest

  • rawRequest(url: string, method: Method, body?: AjaxRequest["body"]): Promise<void | T[]>
  • 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[]>

Request Functions Methods

delete

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

    Parameters

    • Optional body: AjaxRequest["body"]

    Returns Promise<void | T[]>

fetchCurrent

  • fetchCurrent(): Promise<T | undefined>
  • fetch Current Item data from server Allowed path suffix automately preserve data to this._currentData and this.data useCurrentData will affected by update

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

    Returns Promise<T | undefined>

get

  • get(): Promise<undefined | void | T[]>
  • 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<undefined | void | T[]>

getAll

  • getAll(): Promise<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() ;

    Returns Promise<T[]>

getMore

  • fetch more context datas from server append these data to this.data preserve the data to this.rawData and this.data Every fetch success for change the data Scroll a container to load more page datas

    await client.page(2).getMore()  // will fetch from http://url
    await client.getMore()   // not page params , asume this._page is 1 , then it will automatically load data from page 2
    await client.getMore().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").getMore()  // fetch from url `http://newurl`
    await client.path('all/').getMore()    // fetch from url  `http://url/all/`

    getMore() with page , size and query arguments

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

    You can custom your data parse function

      await dataClient.page(3).getMore({
       parseFn: (prevData, currentData) => {
        return [...currentData, ...prevData]
       }
     })

    Parameters

    • Default value __namedParameters: { parseFn: undefined | ParseFnForLoadMore } = {}
      • parseFn: undefined | ParseFnForLoadMore

        Custom the methods to handle the data callback , You can append or prepend the data to origin or make any validation

    Returns Promise<T[]>

option

  • option(body?: AjaxRequest["body"]): Promise<void | T[]>
  • Parameters

    • Optional body: AjaxRequest["body"]

    Returns Promise<void | T[]>

patch

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

    Parameters

    • Optional body: AjaxRequest["body"]

    Returns Promise<void | T[]>

post

  • post(body?: AjaxRequest["body"]): Promise<void | T[]>
  • 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<void | T[]>

put

  • put(body?: AjaxRequest["body"]): Promise<void | T[]>
  • 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<void | T[]>

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