Skip to content

Commit 33f231f

Browse files
authored
Merge pull request #661 from chantouchsek/fix/660-form-type
Fix/660 form type
2 parents 3d20f4a + 64510d0 commit 33f231f

File tree

16 files changed

+80
-160
lines changed

16 files changed

+80
-160
lines changed

.eslintrc

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,15 @@
1919
"@typescript-eslint/no-explicit-any": 0,
2020
"@typescript-eslint/explicit-function-return-type": 0,
2121
"@typescript-eslint/explicit-module-boundary-types": "off",
22+
"@typescript-eslint/consistent-type-imports": ["error", { "disallowTypeAnnotations": false }],
2223
"no-prototype-builtins": "off",
23-
"no-useless-escape": "off"
24+
"no-useless-escape": "off",
25+
"import/order": [
26+
"error",
27+
{
28+
"groups": ["type", "builtin", "external", "internal", "index", "sibling", "parent", "object"],
29+
"alphabetize": { "order": "asc" }
30+
}
31+
]
2432
}
2533
}

nuxt/index.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { resolve, join } from 'path'
1+
import { resolve, join } from 'node:path'
22

33
module.exports = function nuxtAxiosHttpModule(moduleOptions = {}) {
44
const { axiosHttp = {} } = this.options
@@ -9,7 +9,6 @@ module.exports = function nuxtAxiosHttpModule(moduleOptions = {}) {
99
src: resolve(__dirname, './templates/plugin.js'),
1010
fileName: join('vue-nuxt-axios.js'),
1111
})
12-
// this.options.build.transpile.push(/^escape-string-regexp/)
1312
}
1413

1514
// required by nuxt

nuxt/templates/plugin.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import AxiosHttp, { BaseService, Validator } from 'vue-axios-http'
44
const errorProperty = '<%= options.errorProperty %>'
55
const parsedQs = '<%= options.parsedQs %>'
66

7-
Vue.use(AxiosHttp, { errorProperty: errorProperty, parsedQs })
7+
Vue.use(AxiosHttp, { errorProperty, parsedQs })
88

99
export default function ({ $axios }, inject) {
1010
BaseService.$http = $axios

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
"@types/qs": "^6.9.7",
5656
"@typescript-eslint/eslint-plugin": "^5.49.0",
5757
"@typescript-eslint/parser": "^5.9.0",
58-
"@vitest/coverage-c8": "^0.28.1",
58+
"@vitest/coverage-c8": "^0.28.2",
5959
"@vue/test-utils": "^1.3.3",
6060
"axios-mock-adapter": "^1.20.0",
6161
"eslint": "^8.13.0",
@@ -74,7 +74,7 @@
7474
"ts-node": "^10.9.1",
7575
"typescript": "^4.9.4",
7676
"vite": "^4.0.4",
77-
"vitest": "^0.28.1",
77+
"vitest": "^0.28.2",
7878
"vue": "^2.7.14"
7979
},
8080
"files": [

src/__tests__/base-service.test.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1+
import type { ValidatorType } from '../core/Validator'
12
import Axios from 'axios'
2-
import BaseService from '../core/BaseService'
33
import MockAdapter from 'axios-mock-adapter'
4-
import PostService from '../util/PostService'
5-
import type { ValidatorType } from '../core/Validator'
6-
import Validator from '../core/Validator'
74
import { merge } from 'lodash'
5+
import BaseService from '../core/BaseService'
6+
import Validator from '../core/Validator'
7+
import PostService from '../util/PostService'
88

99
let service: PostService
1010
let mockAdapter: MockAdapter
@@ -22,7 +22,7 @@ describe('BaseService', () => {
2222
})
2323

2424
it('check if http was installed', async () => {
25-
BaseService.$http = undefined as any
25+
BaseService.$http = undefined as never
2626
try {
2727
await service.all()
2828
} catch (e) {

src/__tests__/package.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1+
import { mount } from '@vue/test-utils'
12
import Vue from 'vue'
23
import AxiosHttp from '../'
34
import { addElemWithDataAppToBody, disableTransitions, sleep } from '../util'
4-
import { mount } from '@vue/test-utils'
55

66
describe('Vue Api Queries', () => {
77
disableTransitions()

src/__tests__/post-service.spec.ts

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import Axios from 'axios'
2+
import MockAdapter from 'axios-mock-adapter'
23
import BaseService from '../core/BaseService'
34
import PostService from '../util/PostService'
4-
import MockAdapter from 'axios-mock-adapter'
55

66
let service: PostService
77
let mockAdapter: MockAdapter
@@ -33,21 +33,4 @@ describe('PostService', () => {
3333
expect(data.length).toEqual(1)
3434
expect(item.pagination.page).toEqual(1)
3535
})
36-
it('it should throw exception if method is not inlist', async () => {
37-
const items = {
38-
data: [{ name: 'Chantouch', post_id: 1 }],
39-
meta: {
40-
pagination: { count: 1, page: 1, perPage: 20 },
41-
include: [],
42-
},
43-
}
44-
mockAdapter.onGet('/posts/1/tags').reply(500, items)
45-
try {
46-
await service.throwException(1)
47-
} catch (e: any) {
48-
expect(e.message).toEqual(
49-
'`unlink` is not a valid request type, must be one of: `get`, `GET`, `delete`, `DELETE`, `head`, `HEAD`, `options`, `OPTIONS`, `post`, `POST`, `put`, `PUT`, `patch`, `PATCH`.',
50-
)
51-
}
52-
})
5336
})

src/core/BaseService.ts

Lines changed: 25 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
import type { AxiosError, AxiosInstance, AxiosResponse, Method, AxiosRequestConfig } from 'axios'
2-
import type { Errors } from '..'
3-
import Validator from './Validator'
4-
import { hasFiles, objectToFormData, removeDoubleSlash } from '../util'
1+
import type { ValidatorType } from './Validator'
2+
import type { AxiosError, AxiosInstance, Method, AxiosRequestConfig, AxiosResponse } from 'axios'
3+
import type { IParseOptions } from 'qs'
54
import { isObject, isArray } from 'lodash'
6-
import qs, { IParseOptions } from 'qs'
5+
import qs from 'qs'
6+
import Validator from './Validator'
7+
import { hasFiles, objectToFormData } from '../util'
78

89
const validator = Validator
910
const UNPROCESSABLE_ENTITY = 422
@@ -13,7 +14,7 @@ interface AxiosResponseData {
1314
}
1415

1516
class BaseService {
16-
errors: Errors
17+
errors: ValidatorType
1718
parameters: Record<string, any>
1819
endpoint: string
1920
static $http: AxiosInstance
@@ -62,9 +63,7 @@ class BaseService {
6263
const parameter = id && !isObject(id) ? `/${id}` : ''
6364
const body = isObject(id) ? id : payload
6465
const requestType: Method = hasFiles(body) ? 'post' : 'put'
65-
if (hasFiles(body)) {
66-
Object.assign(body, { _method: 'put' })
67-
}
66+
if (hasFiles(body)) Object.assign(body, { _method: 'put' })
6867
return this.submit<T>(requestType, parameter, body, config)
6968
}
7069

@@ -86,18 +85,25 @@ class BaseService {
8685
return this.delete<T>(id)
8786
}
8887

89-
submit<T = any>(method: Method, parameter?: string | number, form?: T, config?: AxiosRequestConfig): Promise<T> {
90-
BaseService.__validateRequestType(method)
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) {
9197
this.beforeSubmit()
92-
return new Promise((resolve, reject) => {
98+
return new Promise<AxiosResponse<T>>((resolve, reject) => {
9399
const data = hasFiles(form) ? objectToFormData(form) : form
94-
const endpoint = parameter ? `/${this.endpoint}/${parameter}` : `/${this.endpoint}`
95-
const url = this.__getParameterString(removeDoubleSlash(endpoint))
100+
const endpoint = param ? `/${this.endpoint}/${param}` : `/${this.endpoint}`
101+
const url = this.__getParameterString(endpoint.replace(/\/\//g, '/'))
96102
config = Object.assign({}, config, { url, data, method })
97103
this.$http(config)
98-
.then((response: AxiosResponse) => {
104+
.then((response) => {
99105
this.onSuccess()
100-
resolve(response.data)
106+
resolve(response)
101107
})
102108
.catch((error: AxiosError<AxiosResponseData>) => {
103109
this.errors.processing = false
@@ -115,39 +121,10 @@ class BaseService {
115121
}
116122

117123
private __getParameterString(url: string) {
118-
const query = qs.stringify(this.parameters, {
119-
encode: false,
120-
skipNulls: true,
121-
addQueryPrefix: true,
122-
})
124+
const query = qs.stringify(this.parameters, { encode: false, skipNulls: true, addQueryPrefix: true })
123125
return `${url}${query}`
124126
}
125127

126-
private static __validateRequestType(requestType: Method) {
127-
const requestTypes: Method[] = [
128-
'get',
129-
'GET',
130-
'delete',
131-
'DELETE',
132-
'head',
133-
'HEAD',
134-
'options',
135-
'OPTIONS',
136-
'post',
137-
'POST',
138-
'put',
139-
'PUT',
140-
'patch',
141-
'PATCH',
142-
]
143-
if (!requestTypes.includes(requestType)) {
144-
throw new Error(
145-
`\`${requestType}\` is not a valid request type, ` + `must be one of: \`${requestTypes.join('`, `')}\`.`,
146-
)
147-
}
148-
return requestType
149-
}
150-
151128
setParameters(parameters: Record<string, any>): this {
152129
Object.keys(parameters).forEach((key) => {
153130
this.parameters[key] = parameters[key]
@@ -173,9 +150,7 @@ class BaseService {
173150
if (!parameters || !parameters.length) {
174151
this.parameters = []
175152
} else if (isArray(parameters)) {
176-
for (const parameter of parameters) {
177-
delete this.parameters[parameter]
178-
}
153+
for (const parameter of parameters) delete this.parameters[parameter]
179154
}
180155
return this
181156
}
@@ -191,9 +166,7 @@ class BaseService {
191166
}
192167

193168
beforeSubmit() {
194-
if (!this.$http) {
195-
throw new Error('Vue Axios Http, No http library provided.')
196-
}
169+
if (!this.$http) throw new Error('Vue Axios Http, No http library provided.')
197170
this.errors.flush()
198171
this.errors.processing = true
199172
this.errors.successful = false

src/core/Validator.ts

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,8 @@ class Validator {
1313
}
1414

1515
add(field: string, message: string, forceUpdate?: boolean) {
16-
if (this.missed(field)) {
17-
this.errors[field] = []
18-
}
19-
if (!this.errors[field].includes(message)) {
20-
this.errors[field].unshift(message)
21-
}
16+
if (this.missed(field)) this.errors[field] = []
17+
if (!this.errors[field].includes(message)) this.errors[field].unshift(message)
2218
if (forceUpdate) {
2319
this.errors[field] = []
2420
this.errors[field].push(message)
@@ -79,9 +75,7 @@ class Validator {
7975
}
8076
return errors
8177
}
82-
if (!fields.length) {
83-
return Object.keys(this.errors).length > 0
84-
}
78+
if (!fields.length) return Object.keys(this.errors).length > 0
8579
const errors: Record<string, any> = {}
8680
fields.forEach((key: string) => (errors[key] = this.get(key)))
8781
return Object.keys(errors).length > 0

src/index.ts

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,35 @@
11
import type { ValidatorType } from './core/Validator'
2+
import type { IParseOptions } from 'qs'
3+
import type _Vue from 'vue'
4+
import { merge } from 'lodash'
25
import BaseService from './core/BaseService'
36
import Validator from './core/Validator'
4-
import { merge } from 'lodash'
5-
import _Vue from 'vue'
67

78
// augment typings of Vue.js
89
import './vue'
910

10-
export type Errors = ValidatorType
11-
export type { ValidatorType }
12-
1311
class AxiosHttp {
1412
installed = false
15-
parsedQs = {
13+
parsedQs: IParseOptions = {
1614
comma: true,
1715
allowDots: true,
1816
ignoreQueryPrefix: true,
1917
}
2018
install(Vue: typeof _Vue, options: Record<string, any> = {}) {
2119
if (this.installed) return
2220
this.installed = true
23-
const defaultOption = merge(
24-
{
25-
parsedQs: this.parsedQs,
26-
errorProperty: 'errors',
27-
},
28-
options,
29-
)
21+
const defaultOption = merge({ parsedQs: this.parsedQs, errorProperty: 'errors' }, options)
3022
const { $axios, errorProperty, parsedQs } = defaultOption
3123
BaseService.$http = $axios
3224
BaseService.$errorProperty = errorProperty || 'errors'
33-
BaseService.$parsedQs = parsedQs || this.parsedQs
25+
BaseService.$parsedQs = parsedQs
3426
Vue.mixin({
3527
beforeCreate() {
36-
this.$options.$errors = {} as any
28+
this.$options.$errors = {} as never
3729
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
3830
// @ts-ignore
3931
Vue.util.defineReactive(this.$options, '$errors', Validator)
40-
if (!this.$options.computed) {
41-
this.$options.computed = {}
42-
}
32+
if (!this.$options.computed) this.$options.computed = {}
4333
this.$options.computed.$errors = function () {
4434
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
4535
// @ts-ignore
@@ -49,6 +39,8 @@ class AxiosHttp {
4939
})
5040
}
5141
}
52-
export { Validator, BaseService }
42+
5343
export * from './util'
44+
export type { ValidatorType }
45+
export { Validator, BaseService }
5446
export default new AxiosHttp()

0 commit comments

Comments
 (0)