add publish action to NetworkClient

This commit is contained in:
Inhji 2023-06-10 08:36:16 +02:00
parent 83d3c6d647
commit 8c74bc607b
3 changed files with 48 additions and 13 deletions

View File

@ -1,4 +1,5 @@
import { NetworkRequest } from '@networking/NetworkRequest'
import { PublishResponse } from './PublishResponse'
export interface NetworkClientInterface {
@ -6,6 +7,7 @@ export interface NetworkClientInterface {
// and returns a Promise. `T` specifies the return type and is used
// by the network client to decode the network payload.
run<T>(request: NetworkRequest): Promise<T>
publish(request: NetworkRequest): Promise<PublishResponse>
}
/*
@ -24,29 +26,62 @@ export class NetworkClient implements NetworkClientInterface {
// Life cycle
constructor(
appToken: () => string
appToken: () => string,
) {
this.appToken = appToken
}
private requestHeaders(): HeadersInit {
return {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Bearer ' + this.appToken()
}
}
// Public
public async run<T>(request: NetworkRequest): Promise<T> {
const url = 'https://micro.blog' + request.path + '?' + request.parameters
const url = request.url + '?' + request.parameters
const response = await fetch(url, {
method: request.method,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + this.appToken()
}
headers: this.requestHeaders(),
body: request.body
})
if (!response.ok) {
throw new Error('Network error: ' + response.status)
throw new Error(
`Network error: ${response.status}`
)
}
return await response.json() as T
}
public async publish(request: NetworkRequest): Promise<PublishResponse> {
const response: Response = await fetch(request.url, {
method: request.method,
headers: this.requestHeaders(),
body: request.body
})
if (!response.ok) {
throw new Error(
`Network error: ${response.status}`
)
}
const postUrl: string | null = response.headers.get("Location") || response.headers.get("location")
if (!postUrl) {
throw new Error(
"Response is missing url of new post."
)
}
return {
url: postUrl
}
}
}

View File

@ -4,7 +4,7 @@
* body sent.
*/
export type NetworkRequest = {
path: string
url: string
parameters: URLSearchParams
method: string
body?: string

View File

@ -149,7 +149,7 @@ export class PublishViewModel implements TagSuggestionDelegate {
this.delegate?.publishDidValidateDate()
try {
const response = this.networkRequestFactory.makePublishRequest(
const request = this.networkRequestFactory.makePublishRequest(
this.title,
this.content,
this.tags,
@ -158,11 +158,11 @@ export class PublishViewModel implements TagSuggestionDelegate {
this.formattedScheduledDate()
)
const result = await this.networkClient.run<PublishResponse>(
response
const response: PublishResponse = await this.networkClient.publish(
request
)
this.delegate?.publishDidSucceed(result)
this.delegate?.publishDidSucceed(response)
} catch (error) {
this.delegate?.publishDidFail(error)
}