These are definitely temporary tests, as testing the lcient API will become more difficult and require more infrastructure as real data starts entering the system.
77 lines
2.5 KiB
TypeScript
77 lines
2.5 KiB
TypeScript
import { VResponse, SessionId, UserOverview } from '../gen/types'
|
|
|
|
export interface Client {
|
|
auth: (
|
|
username: string,
|
|
password: string,
|
|
) => Promise<ClientResponse<SessionId>>
|
|
|
|
listUsers: (sessionId: SessionId) => Promise<ClientResponse<UserOverview[]>>
|
|
}
|
|
|
|
export type ClientResponse<A> =
|
|
| { status: 'ok'; content: A }
|
|
| { status: 'password-reset'; content: SessionId }
|
|
| { status: 'unauthorized' }
|
|
| { status: 'unexpected'; code: number }
|
|
|
|
export class Connection implements Client {
|
|
private base: URL
|
|
|
|
constructor(baseUrl: URL) {
|
|
this.base = baseUrl
|
|
}
|
|
|
|
async auth(
|
|
username: string,
|
|
password: string,
|
|
): Promise<ClientResponse<SessionId>> {
|
|
const url = new URL(this.base)
|
|
url.pathname = `/api/test/auth`
|
|
const response = await fetch(url, {
|
|
method: 'POST',
|
|
headers: [['Content-Type', 'application/json']],
|
|
body: JSON.stringify({ username: username, password: password }),
|
|
})
|
|
if (response.ok) {
|
|
let resp = await response.json()
|
|
switch (resp.type) {
|
|
case 'success':
|
|
return { status: 'ok', content: resp.content }
|
|
case 'password-reset':
|
|
return { status: 'password-reset', content: resp.content }
|
|
}
|
|
return { status: 'ok', content: resp }
|
|
} else if (response.status == 401) {
|
|
return { status: 'unauthorized' }
|
|
} else {
|
|
return { status: 'unexpected', code: response.status }
|
|
}
|
|
}
|
|
|
|
async listUsers(
|
|
sessionId: SessionId,
|
|
): Promise<ClientResponse<UserOverview[]>> {
|
|
const url = new URL(this.base)
|
|
url.pathname = `/api/test/list-users`
|
|
const response = await fetch(url, {
|
|
method: 'GET',
|
|
headers: [['Authorization', `Bearer ${sessionId}`]],
|
|
})
|
|
if (response.ok) {
|
|
let resp = await response.json()
|
|
switch (resp.type) {
|
|
case 'success':
|
|
return { status: 'ok', content: resp.content }
|
|
case 'password-reset':
|
|
return { status: 'password-reset', content: resp.content }
|
|
}
|
|
return { status: 'ok', content: resp }
|
|
} else if (response.status == 401) {
|
|
return { status: 'unauthorized' }
|
|
} else {
|
|
return { status: 'unexpected', code: response.status }
|
|
}
|
|
}
|
|
}
|