diff --git a/apps/cacvote-mark/backend/src/cacvote-server/client.ts b/apps/cacvote-mark/backend/src/cacvote-server/client.ts index 0a1f635b0..977bfbbb5 100644 --- a/apps/cacvote-mark/backend/src/cacvote-server/client.ts +++ b/apps/cacvote-mark/backend/src/cacvote-server/client.ts @@ -1,5 +1,11 @@ import { Buffer } from 'buffer'; -import { Result, asyncResultBlock, err, ok } from '@votingworks/basics'; +import { + Optional, + Result, + asyncResultBlock, + err, + ok, +} from '@votingworks/basics'; import fetch, { Headers, Request } from 'cross-fetch'; import { safeParse } from '@votingworks/types'; import { ZodError, z } from 'zod'; @@ -31,55 +37,40 @@ export class Client { * Check that the server is responding. */ async checkStatus(): Promise> { - const statusResult = await this.get('/api/status'); - - if (statusResult.isErr()) { - return statusResult; - } - - const response = statusResult.ok(); - if (!response.ok) { - return err({ type: 'network', message: response.statusText }); - } + return asyncResultBlock(async (bail) => { + const response = (await this.get('/api/status')).okOrElse(bail); - return ok(); + if (!response.ok) { + bail({ type: 'network', message: response.statusText }); + } + }); } /** * Create an object on the server. */ async createObject(signedObject: SignedObject): Promise> { - const postResult = await this.post( - '/api/objects', - JSON.stringify(signedObject) - ); - - if (postResult.isErr()) { - return postResult; - } - - const response = postResult.ok(); - if (!response.ok) { - return err({ type: 'network', message: response.statusText }); - } - - const uuidResult = safeParse(UuidSchema, await response.text()); + return asyncResultBlock(async (bail) => { + const response = ( + await this.post('/api/objects', JSON.stringify(signedObject)) + ).okOrElse(bail); - if (uuidResult.isErr()) { - return err({ - type: 'schema', - error: uuidResult.err(), - message: uuidResult.err().message, - }); - } + if (!response.ok) { + bail({ type: 'network', message: response.statusText }); + } - return uuidResult; + return safeParse(UuidSchema, await response.text()).okOrElse( + (error) => bail({ type: 'schema', error, message: error.message }) + ); + }); } /** * Retrieve an object from the server. */ - async getObjectById(uuid: Uuid): Promise> { + async getObjectById( + uuid: Uuid + ): Promise>> { const SignedObjectRawSchema = z.object({ payload: z.string(), certificates: z.string(), @@ -88,6 +79,11 @@ export class Client { return asyncResultBlock(async (bail) => { const response = (await this.get(`/api/objects/${uuid}`)).okOrElse(bail); + if (response.status === 404) { + // not found + return undefined; + } + if (!response.ok) { bail({ type: 'network', message: response.statusText }); } @@ -133,7 +129,7 @@ export class Client { ).okOrElse(bail); if (!response.ok) { - return err({ type: 'network', message: response.statusText }); + bail({ type: 'network', message: response.statusText }); } const entries = safeParse(