feat: convert abstractService to ts

This commit is contained in:
Dominik Pschenitschni 2022-02-13 21:40:39 +01:00
parent c6d214b9eb
commit c70cbf4fb4
Signed by: dpschen
GPG Key ID: B257AC0149F43A77
1 changed files with 49 additions and 101 deletions

View File

@ -1,6 +1,15 @@
import axios from 'axios'
import axios, {Method} from 'axios'
import {objectToSnakeCase} from '@/helpers/case'
import {getToken} from '@/helpers/auth'
import AbstractModel from '@/models/abstractModel'
interface Paths {
create : string
get : string
getAll : string
update : string
delete : string
}
function convertObject(o) {
if (o instanceof Date) {
@ -33,10 +42,10 @@ export default class AbstractService {
// Initial variable definitions
///////////////////////////
http = null
http
loading = false
uploadProgress = 0
paths = {
paths: Paths = {
create: '',
get: '',
getAll: '',
@ -53,14 +62,12 @@ export default class AbstractService {
/**
* The abstract constructor.
* @param [paths] An object with all paths. Default values are specified above.
* @param [paths] An object with all paths.
*/
constructor(paths) {
constructor(paths : Partial<Paths> = {}) {
this.http = axios.create({
baseURL: window.API_URL,
headers: {
'Content-Type': 'application/json',
},
headers: { 'Content-Type': 'application/json' },
})
// Set the interceptors to process every request
@ -94,38 +101,27 @@ export default class AbstractService {
this.http.defaults.headers.common['Authorization'] = `Bearer ${token}`
}
if (paths) {
this.paths = {
create: paths.create !== undefined ? paths.create : '',
get: paths.get !== undefined ? paths.get : '',
getAll: paths.getAll !== undefined ? paths.getAll : '',
update: paths.update !== undefined ? paths.update : '',
delete: paths.delete !== undefined ? paths.delete : '',
}
}
Object.assign(this.paths, paths)
}
/**
* Whether or not to use the create interceptor which processes a request payload into json
* @returns {boolean}
*/
useCreateInterceptor() {
useCreateInterceptor(): boolean {
return true
}
/**
* Whether or not to use the update interceptor which processes a request payload into json
* @returns {boolean}
*/
useUpdateInterceptor() {
return true
useUpdateInterceptor(): boolean {
}
/**
* Whether or not to use the delete interceptor which processes a request payload into json
* @returns {boolean}
*/
useDeleteInterceptor() {
useDeleteInterceptor(): boolean {
return true
}
@ -135,10 +131,8 @@ export default class AbstractService {
/**
* Returns an object with all route parameters and their values.
* @param route
* @returns object
*/
getRouteReplacements(route, parameters = {}) {
getRouteReplacements(route : string, parameters = {}) {
const replace$$1 = {}
let pattern = this.getRouteParameterPattern()
pattern = new RegExp(pattern instanceof RegExp ? pattern.source : pattern, 'g')
@ -152,22 +146,18 @@ export default class AbstractService {
/**
* Holds the replacement pattern for url paths, can be overwritten by implementations.
* @return {RegExp}
*/
getRouteParameterPattern() {
getRouteParameterPattern(): RegExp {
return /{([^}]+)}/
}
/**
* Returns a fully-ready-ready-to-make-a-request-to route with replaced parameters.
* @param path
* @param pathparams
* @return string
*/
getReplacedRoute(path, pathparams) {
getReplacedRoute(path : string, pathparams : {}) : string {
const replacements = this.getRouteReplacements(path, pathparams)
return Object.entries(replacements).reduce(
(result, [parameter, value]) => result.replace(parameter, value),
(result, [parameter, value]) => result.replace(parameter, value as string),
path,
)
}
@ -178,9 +168,8 @@ export default class AbstractService {
* case the api returns a response in < 100ms.
* But because the timeout is created using setTimeout, it will still trigger even if the request is
* already finished, so we return a method to call in that case.
* @returns {Function}
*/
setLoading() {
setLoading(): Function {
const timeout = setTimeout(() => {
this.loading = true
}, 100)
@ -200,46 +189,36 @@ export default class AbstractService {
/**
* The modelFactory returns an model from an object.
* This one here is the default one, usually the service definitions for a model will override this.
* @param data
* @returns {*}
*/
modelFactory(data) {
return data
modelFactory(data : Partial<AbstractModel>) {
return new AbstractModel(data)
}
/**
* This is the model factory for get requests.
* @param data
* @return {*}
*/
modelGetFactory(data) {
modelGetFactory(data : Partial<AbstractModel>) {
return this.modelFactory(data)
}
/**
* This is the model factory for get all requests.
* @param data
* @return {*}
*/
modelGetAllFactory(data) {
modelGetAllFactory(data : Partial<AbstractModel>) {
return this.modelFactory(data)
}
/**
* This is the model factory for create requests.
* @param data
* @return {*}
*/
modelCreateFactory(data) {
modelCreateFactory(data : Partial<AbstractModel>) {
return this.modelFactory(data)
}
/**
* This is the model factory for update requests.
* @param data
* @return {*}
*/
modelUpdateFactory(data) {
modelUpdateFactory(data : Partial<AbstractModel>) {
return this.modelFactory(data)
}
@ -249,37 +228,29 @@ export default class AbstractService {
/**
* Default preprocessor for get requests
* @param model
* @return {*}
*/
beforeGet(model) {
beforeGet(model : InstanceType<typeof AbstractModel>) {
return model
}
/**
* Default preprocessor for create requests
* @param model
* @return {*}
*/
beforeCreate(model) {
beforeCreate(model : InstanceType<typeof AbstractModel>) {
return model
}
/**
* Default preprocessor for update requests
* @param model
* @return {*}
*/
beforeUpdate(model) {
beforeUpdate(model : InstanceType<typeof AbstractModel>) {
return model
}
/**
* Default preprocessor for delete requests
* @param model
* @return {*}
*/
beforeDelete(model) {
beforeDelete(model : InstanceType<typeof AbstractModel>) {
return model
}
@ -291,9 +262,8 @@ export default class AbstractService {
* Performs a get request to the url specified before.
* @param model The model to use. The request path is built using the values from the model.
* @param params Optional query parameters
* @returns {Q.Promise<any>}
*/
get(model, params = {}) {
get(model : InstanceType<typeof AbstractModel>, params = {}) {
if (this.paths.get === '') {
throw new Error('This model is not able to get data.')
}
@ -304,12 +274,8 @@ export default class AbstractService {
/**
* This is a more abstract implementation which only does a get request.
* Services which need more flexibility can use this.
* @param url
* @param model
* @param params
* @returns {Q.Promise<unknown>}
*/
async getM(url, model = {}, params = {}) {
async getM(url : string, model = new AbstractModel({}), params = {}) {
const cancel = this.setLoading()
model = this.beforeGet(model)
@ -325,12 +291,12 @@ export default class AbstractService {
}
}
async getBlobUrl(url, method = 'GET', data = {}) {
async getBlobUrl(url : string, method = 'GET' as Method, data = {}) {
const response = await this.http({
url: url,
method: method,
url,
method,
responseType: 'blob',
data: data,
data,
})
return window.URL.createObjectURL(new Blob([response.data]))
}
@ -341,9 +307,8 @@ export default class AbstractService {
* @param model The model to use. The request path is built using the values from the model.
* @param params Optional query parameters
* @param page The page to get
* @returns {Q.Promise<any>}
*/
async getAll(model = {}, params = {}, page = 1) {
async getAll(model : InstanceType<typeof AbstractModel> = new AbstractModel({}), params = {}, page = 1) {
if (this.paths.getAll === '') {
throw new Error('This model is not able to get data.')
}
@ -374,10 +339,9 @@ export default class AbstractService {
/**
* Performs a put request to the url specified before
* @param model
* @returns {Promise<any | never>}
*/
async create(model) {
async create(model : InstanceType<typeof AbstractModel>) {
if (this.paths.create === '') {
throw new Error('This model is not able to create data.')
}
@ -400,11 +364,8 @@ export default class AbstractService {
/**
* An abstract implementation to send post requests.
* Services can use this to implement functions to do post requests other than using the update method.
* @param url
* @param model
* @returns {Q.Promise<unknown>}
*/
async post(url, model) {
async post(url : string, model : InstanceType<typeof AbstractModel>) {
const cancel = this.setLoading()
try {
@ -421,10 +382,8 @@ export default class AbstractService {
/**
* Performs a post request to the update url
* @param model
* @returns {Q.Promise<any>}
*/
update(model) {
update(model : InstanceType<typeof AbstractModel>) {
if (this.paths.update === '') {
throw new Error('This model is not able to update data.')
}
@ -435,10 +394,8 @@ export default class AbstractService {
/**
* Performs a delete request to the update url
* @param model
* @returns {Q.Promise<any>}
*/
async delete(model) {
async delete(model : InstanceType<typeof AbstractModel>) {
if (this.paths.delete === '') {
throw new Error('This model is not able to delete data.')
}
@ -459,21 +416,15 @@ export default class AbstractService {
* @param url
* @param file
* @param fieldName The name of the field the file is uploaded to.
* @returns {Q.Promise<unknown>}
*/
uploadFile(url, file, fieldName) {
uploadFile(url : string, file, fieldName : string) {
return this.uploadBlob(url, new Blob([file]), fieldName, file.name)
}
/**
* Uploads a blob to a url.
* @param url
* @param blob
* @param fieldName
* @param filename
* @returns {Q.Promise<unknown>}
*/
uploadBlob(url, blob, fieldName, filename) {
uploadBlob(url : string, blob, fieldName, filename : string) {
const data = new FormData()
data.append(fieldName, blob, filename)
return this.uploadFormData(url, data)
@ -481,11 +432,8 @@ export default class AbstractService {
/**
* Uploads a form data object.
* @param url
* @param formData
* @returns {Q.Promise<unknown>}
*/
async uploadFormData(url, formData) {
async uploadFormData(url : string, formData) {
const cancel = this.setLoading()
try {
const response = await this.http.put(