Skip to content

Commit

Permalink
Add PHPResponse.forHttpCode() shorthand (#1322)
Browse files Browse the repository at this point in the history
Short and sweet – adds a `PHPResponse.forHttpCode()` method to
streamline the creation of various OK and error response objects.

For example:

```ts
// Before
const error500 = new PHPResponse(500, {}, new TextEncoder().encode("Internal Server Error"))

// After
const error500 = PHPResponse.forHttpCode(500);
```

 ## Testing instructions

None, this PR only adds new code without using it just yet.
  • Loading branch information
adamziel authored Apr 25, 2024
1 parent 349e0e6 commit 8dae0ca
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions packages/php-wasm/universal/src/lib/php-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,22 @@ export interface PHPResponseData {
readonly httpStatusCode: number;
}

const responseTexts: Record<number, string> = {
500: 'Internal Server Error',
502: 'Bad Gateway',
404: 'Not Found',
403: 'Forbidden',
401: 'Unauthorized',
400: 'Bad Request',
301: 'Moved Permanently',
302: 'Found',
307: 'Temporary Redirect',
308: 'Permanent Redirect',
204: 'No Content',
201: 'Created',
200: 'OK',
};

/**
* PHP response. Body is an `ArrayBuffer` because it can
* contain binary data.
Expand Down Expand Up @@ -68,6 +84,16 @@ export class PHPResponse implements PHPResponseData {
this.errors = errors;
}

static forHttpCode(httpStatusCode: number, text = '') {
return new PHPResponse(
httpStatusCode,
{},
new TextEncoder().encode(
text || responseTexts[httpStatusCode] || ''
)
);
}

static fromRawData(data: PHPResponseData): PHPResponse {
return new PHPResponse(
data.httpStatusCode,
Expand Down

0 comments on commit 8dae0ca

Please sign in to comment.