Skip to content

Commit 0bb4ef1

Browse files
authored
Merge pull request #780 from chantouchsek/feat/779-add-remove-parameter-option
Feat/779 add remove parameter option
2 parents cb8c588 + 2be5455 commit 0bb4ef1

File tree

6 files changed

+85
-52
lines changed

6 files changed

+85
-52
lines changed

.github/workflows/ci.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ jobs:
1414
runs-on: ${{ matrix.os }}
1515
strategy:
1616
matrix:
17-
node-version: [16]
18-
os: [ubuntu-latest, macOS-latest]
17+
node-version: [18]
18+
os: [ubuntu-latest]
1919

2020
steps:
2121
- uses: actions/[email protected]

README.md

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ classes. Keep your code clean and elegant.
1212
Wouldn't it be great if you could just use your back end to validate forms on the front end? This package provides a
1313
`BaseService` class that does exactly that. It can post itself to a configured endpoint and manage errors. The class is
1414
meant to be used with a Laravel back end, and it doesn't limit that you need only to work with laravel, Ruby on Rail,
15-
NodeJs, ExpressJs, or any other languages.
15+
Node.js, Express.js, or any other languages.
1616

1717
Take a look at the [usage section](#usage) to view a detailed example on how to use it.
1818

@@ -47,16 +47,16 @@ export default {
4747
// simple usage
4848
'vue-axios-http/nuxt',
4949
// With options
50-
['vue-axios-http/nuxt', { errorProperty: 'errors' }],
50+
['vue-axios-http/nuxt', { errorProperty: 'errors', resetParameter: true }],
5151
'@nuxtjs/axios',
5252
],
53-
axiosHttp: { errorProperty: 'errors' },
53+
axiosHttp: { errorProperty: 'errors', resetParameter: true },
5454
}
5555
```
5656

5757
### Options
5858

59-
you can overwrite it, by adding in config above.
59+
you can overwrite it by adding in the config above.
6060

6161
### Note:
6262

@@ -94,7 +94,7 @@ Vue.use(AxiosHttp)
9494

9595
### Note
9696

97-
Error response must look like: or base on **errorProperty** from config
97+
Error response must look like: or based on **errorProperty** from config
9898

9999
```json
100100
{
@@ -137,7 +137,7 @@ $errors.first(['name[0]']) // return object like
137137
$errors.first(['name[0].kh']) // return string like
138138
```
139139

140-
## Using with Vuex
140+
## Using it with Vuex
141141

142142
1.Create **proxies** folder or your prefer folder name for this
143143

@@ -296,7 +296,7 @@ export default {
296296

297297
You can set or remove any parameters you like.
298298

299-
## Service's methods are available
299+
## Service methods are available
300300

301301
| Method | Description |
302302
| ----------------------------------------------- | --------------------------- |
@@ -310,7 +310,7 @@ You can set or remove any parameters you like.
310310

311311
Set parameters with key/value.
312312

313-
**Note**: If you to pass query string as object that can be response like object format at api side.
313+
**Note**: If you to pass query string, as an object that can be response like object format at api side.
314314

315315
#### Example
316316

@@ -335,13 +335,13 @@ const { data } = service.setParameters(parameters).all()
335335
this.data = data
336336
```
337337

338-
**Note**: Query object above will transform into query string like:
338+
**Note**: A query object above will transform into query string like:
339339

340340
```text
341341
https://my-web-url.com?search[first_name]=Sek&search[last_name]=Chantouch&page[limit]=10&page[offset]=1&order[first_name]=asc&order[last_name]=desc&category_id=6
342342
```
343343

344-
if setParameter that value is empty or null it will remove that param for query string
344+
if setParameter that value is empty or null, it will remove that param for query string
345345

346346
#### setParameter()
347347

@@ -426,7 +426,7 @@ It can be called by `this.$errors.**`
426426
| **has(attributes)** | To check multiple attributes given have any errors |
427427
| **first(attribute)** | To get errors message by an attribute |
428428

429-
## How to use in vue component
429+
## How to use in a vue component
430430

431431
```vue
432432
<template>

src/__tests__/base-service.test.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ describe('BaseService', () => {
9090
]
9191
mockAdapter.onGet('/posts?id=1&first_name=Dara').reply(200, { data: items })
9292
const { data } = await service.setParameter('id', 1).setParameters({ first_name: 'Dara' }).all()
93+
9394
expect(data).toEqual(items)
9495
})
9596

@@ -341,6 +342,32 @@ describe('BaseService', () => {
341342
expect(service.$http.defaults.baseURL).toBe(undefined)
342343
})
343344
})
345+
describe('BaseService -> Remove parameters', () => {
346+
beforeEach(() => {
347+
validator = Validator
348+
const axios = Axios.create({ baseURL: 'https://mock-api.test' })
349+
BaseService.$http = axios
350+
BaseService.$resetParameter = true
351+
BaseService.$errorProperty = 'message'
352+
353+
service = new PostService()
354+
mockAdapter = new MockAdapter(axios)
355+
mockAdapter.reset()
356+
})
357+
358+
it('should clear the parameters, if the option `resetParameter` is true', async () => {
359+
const items = [
360+
{ first_name: 'Dara', last_name: 'Hok', id: 1 },
361+
{ first_name: 'Chantouch', last_name: 'Sek', id: 2 },
362+
]
363+
mockAdapter.onGet('/posts?id=1&first_name=Dara').reply(200, { data: items })
364+
const parameters = { first_name: 'Dara', id: 1 }
365+
const { data } = await service.setParameter('id', 1).setParameters(parameters).all()
366+
367+
expect(data).toEqual(items)
368+
expect(service.parameters).toEqual({})
369+
})
370+
})
344371

345372
function getFormDataKeys(formData: any) {
346373
// This is because the FormData.keys() is missing from the jsdom implementations.

src/core/BaseService.ts

Lines changed: 23 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import type { ValidatorType } from './Validator'
21
import type { AxiosError, AxiosInstance, Method, AxiosRequestConfig, AxiosResponse } from 'axios'
32
import type { IParseOptions } from 'qs'
43
import { isObject, isArray } from 'lodash'
@@ -13,23 +12,18 @@ interface AxiosResponseData {
1312
[key: string | number]: any
1413
}
1514

16-
class BaseService {
17-
errors: ValidatorType
18-
parameters: Record<string, any>
19-
endpoint: string
15+
export default class BaseService {
16+
public errors = Validator
2017
static $http: AxiosInstance
2118
static $errorProperty = 'errors'
19+
static $resetParameter? = false
2220
static $parsedQs: IParseOptions = {
2321
comma: true,
2422
allowDots: true,
2523
ignoreQueryPrefix: true,
2624
}
2725

28-
constructor(endpoint: string, parameters: Record<string, any>) {
29-
this.endpoint = endpoint
30-
this.parameters = parameters
31-
this.errors = Validator
32-
}
26+
constructor(readonly endpoint: string, public parameters: Record<string, any> = {}) {}
3327

3428
get $http() {
3529
return BaseService.$http
@@ -39,6 +33,10 @@ class BaseService {
3933
return BaseService.$errorProperty
4034
}
4135

36+
get $resetParameter() {
37+
return BaseService.$resetParameter
38+
}
39+
4240
get $parsedQs() {
4341
return BaseService.$parsedQs
4442
}
@@ -85,15 +83,7 @@ class BaseService {
8583
return this.delete<T>(id)
8684
}
8785

88-
submit<T = any>(method: Method, url?: string | number, form?: any, config?: AxiosRequestConfig) {
89-
return new Promise<T>((resolve, reject) => {
90-
this.$submit<T>(method, url, form, config)
91-
.then(({ data }) => resolve(data))
92-
.catch((err) => reject(err))
93-
})
94-
}
95-
96-
$submit<T = any>(method: Method, param?: string | number, form?: any, config?: AxiosRequestConfig) {
86+
$submit<T = any, F = any>(method: Method, param?: string | number, form?: F, config?: AxiosRequestConfig) {
9787
this.beforeSubmit()
9888
return new Promise<AxiosResponse<T>>((resolve, reject) => {
9989
const data = hasFiles(form) ? objectToFormData(form) : form
@@ -117,6 +107,15 @@ class BaseService {
117107
}
118108
reject(error)
119109
})
110+
if (this.$resetParameter) this.removeParameters()
111+
})
112+
}
113+
114+
submit<T = any, F = any>(method: Method, url?: string | number, form?: F, config?: AxiosRequestConfig) {
115+
return new Promise<T>((resolve, reject) => {
116+
this.$submit<T>(method, url, form, config)
117+
.then(({ data }) => resolve(data))
118+
.catch((err) => reject(err))
120119
})
121120
}
122121

@@ -125,14 +124,14 @@ class BaseService {
125124
return `${url}${query}`
126125
}
127126

128-
setParameters(parameters: Record<string, any>): this {
127+
setParameters(parameters: Record<string, any>) {
129128
Object.keys(parameters).forEach((key) => {
130129
this.parameters[key] = parameters[key]
131130
})
132131
return this
133132
}
134133

135-
setParameter(parameter: string, value?: any): this {
134+
setParameter(parameter: string, value?: any) {
136135
if (!value) {
137136
const options: IParseOptions = Object.assign({}, this.$parsedQs, {
138137
comma: true,
@@ -146,16 +145,16 @@ class BaseService {
146145
return this
147146
}
148147

149-
removeParameters(parameters = [] as any[]): this {
148+
removeParameters(parameters: string[] = []) {
150149
if (!parameters || !parameters.length) {
151-
this.parameters = []
150+
this.parameters = {}
152151
} else if (isArray(parameters)) {
153152
for (const parameter of parameters) delete this.parameters[parameter]
154153
}
155154
return this
156155
}
157156

158-
removeParameter(parameter: string): this {
157+
removeParameter(parameter: string) {
159158
delete this.parameters[parameter]
160159
return this
161160
}
@@ -182,5 +181,3 @@ class BaseService {
182181
validator.successful = true
183182
}
184183
}
185-
186-
export default BaseService

src/core/Validator.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,12 @@ import { cloneDeep, get, has, omit } from 'lodash'
22
import { is, toCamelCase, toSnakeCase } from '../util'
33

44
class Validator {
5-
public errors: Record<string, any>
65
public successful: boolean
76
public processing: boolean
87

9-
constructor(errors: Record<string, any> = {}) {
8+
constructor(public errors: Record<string, any> = {}) {
109
this.processing = false
1110
this.successful = false
12-
this.errors = errors
1311
}
1412

1513
add(field: string, message: string, forceUpdate?: boolean) {

src/index.ts

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,21 +8,32 @@ import Validator from './core/Validator'
88
// augment typings of Vue.js
99
import './vue'
1010

11-
class AxiosHttp {
12-
installed = false
13-
parsedQs: IParseOptions = {
11+
interface ModuleOptions {
12+
resetParameter?: boolean
13+
parsedQs: IParseOptions
14+
errorProperty?: string | 'errors' | 'message'
15+
}
16+
const optionDefault: ModuleOptions = {
17+
resetParameter: false,
18+
parsedQs: {
1419
comma: true,
1520
allowDots: true,
1621
ignoreQueryPrefix: true,
17-
}
18-
install(Vue: typeof _Vue, options: Record<string, any> = {}) {
22+
},
23+
errorProperty: 'errors',
24+
}
25+
26+
class AxiosHttp {
27+
installed = false
28+
install(Vue: typeof _Vue, options: Partial<ModuleOptions> = {}) {
1929
if (this.installed) return
30+
2031
this.installed = true
21-
const defaultOption = merge({ parsedQs: this.parsedQs, errorProperty: 'errors' }, options)
22-
const { $axios, errorProperty, parsedQs } = defaultOption
23-
BaseService.$http = $axios
24-
BaseService.$errorProperty = errorProperty || 'errors'
32+
const { errorProperty, parsedQs, resetParameter } = merge(optionDefault, options)
33+
2534
BaseService.$parsedQs = parsedQs
35+
BaseService.$resetParameter = resetParameter
36+
BaseService.$errorProperty = errorProperty || 'errors'
2637
Vue.mixin({
2738
beforeCreate() {
2839
this.$options.$errors = {} as never
@@ -41,6 +52,6 @@ class AxiosHttp {
4152
}
4253

4354
export * from './util'
44-
export type { ValidatorType }
55+
export type { ValidatorType, ModuleOptions }
4556
export { Validator, BaseService }
4657
export default new AxiosHttp()

0 commit comments

Comments
 (0)