The SimpleHttpService class makes it easier to use http methods.
npm install @coheia/simple-http-servicerequestInit.
console
$ npm install @coheia/simple-http-service
`
$3
Import the SimpleHttpService class and its related types as follow:
`typescript
import SimpleHttpService, { Headers, SimpleConfigs } from '@coheia/simple-http-service'
`
$3
`typescript
import SimpleHttpService from '@coheia/simple-http-service'
const api = new SimpleHttpService({
baseUrl: 'http://localhost:3001', // remove for same domain api
baseEndpoint: 'api/v1'
})
// simple get request
const response = await api.get('your/endpoint')
type LoginBody = {
username: string
password: string
}
// simple destruct response
type LoginSuccess = {
accessToken: string
}
const { accessToken } = await api.post('auth/login', {
username: 'admin',
password: '*'
})
`
$3
SimpleConfigs type defines the configuration object (optional) received in the SimpleHttpService class's constructor.
`typescript
import { SimpleConfigs } from '@coheia/simple-http-service';
export const httpServiceConfig: SimpleConfigs = {
baseUrl: 'http://localhost:3001', // don't add for same domain
baseEndpoint: 'api/v1' // prefixed in every method's endpoint param
}
`
$3
If you need to add authentication, you can extend the SimpleHttpService class and override the handleHeaders method.
> 'Content-Type': 'application/json' is default in SimpleHttpService, if override handleHeaders remember to reset it, or not if you preferer other type 👏
`typescript
import SimpleHttpService, { Headers, SimpleConfigs} from '@coheia/simple-http-service'
// Create a subclass called ProtectedService that extends SimpleHttpService.
class ProtectedService extends SimpleHttpService {
private readonly token: string
// The constructor sets the token and calls the parent class's constructor with the config param.
constructor(token: string, config?: SimpleConfigs) {
super(config)
this.token = token
}
protected override handleHeaders(headers: Headers): Headers {
return {
Authorization: Bearer ${this.token},
'Content-Type': 'application/json',
...headers
}
}
}
export const TOKEN = 'your_token'
export const apiProtected = new ProtectedService(TOKEN)
`
$3
The following code manages a CRUD API by creating a ProjectService class that extends a ProtectedService (the JWT example). The code removes the authorization header when the request does not require authentication, which is the case for the getProjects and getProject methods. The code also includes methods for creating, updating, and deleting projects, which make use of the ProtectedService's post, put, and delete methods.
`typescript
import { ProtectedService, TOKEN } from './ProtectedService'
import { removeAuthorizationHeader } from '@coheia/simple-http-service'
const httpServiceConfig = {
baseUrl: 'http://localhost:3001'
}
interface NewProject {
name: string
order?: number
}
interface Project extends NewProject {
id: string
created_at: string
updated_at: string
}
class ProjectService extends ProtectedService {
constructor() {
super(TOKEN, {
...httpServiceConfig,
baseEndpoint: '/projects'
})
}
async getProjects(): Promise {
return await this.get('/', removeAuthorizationHeader)
}
async getProject(id: string): Promise {
return await this.get( /${id}, removeAuthorizationHeader)
}
async createProject(project: NewProject): Promise {
return await this.post('/', project)
}
async updateProject(id: string, project: NewProject): Promise {
return await this.put( /${id}, project)
}
async deleteProject(id: string): Promise {
return await this.delete( /${id})
}
}
export const projectService = new ProjectService()
`
$3
If you are using the same domain for both the API and the client, you can omit the configuration object completely, or individually baseUrl and baseEndpoint like this:
`typescript
import SimpleHttpService from '@coheia/simple-http-service';
//for same domain api without baseEndpoint
const http = new SimpleHttpService();
const project = await http.get('/project/10');
// GET - CLIENT_DOMAIN/project/10
`
`typescript
// and for same domain api with baseEndpoint as api version
const http = new SimpleHttpService({ baseEndpoint: 'api/v3' });
const project = await http.get('/project/10');
// GET - CLIENT_DOMAIN/api/v3/project/10
``