Skip to content

Commit

Permalink
Refactor miscellaneous source files to pass strict-null checks
Browse files Browse the repository at this point in the history
  • Loading branch information
petebacondarwin committed Jan 17, 2022
1 parent 5d423e9 commit edc4b53
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 29 deletions.
5 changes: 5 additions & 0 deletions .changeset/heavy-days-cheat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wrangler": patch
---

Refactor miscellaneous source files to pass strict-null checks
12 changes: 10 additions & 2 deletions packages/wrangler/src/__tests__/kv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,8 +335,16 @@ describe("wrangler", () => {
expect(namespaceId).toEqual(expectedNamespaceId);
expect(key).toEqual(expectedKey);
expect(body).toEqual(expectedValue);
expect(query.get("expiration")).toEqual(`${expiration}`);
expect(query.get("expiration_ttl")).toEqual(`${expirationTtl}`);
if (expiration !== undefined) {
expect(query.get("expiration")).toEqual(`${expiration}`);
} else {
expect(query.has("expiration")).toBe(false);
}
if (expirationTtl) {
expect(query.get("expiration_ttl")).toEqual(`${expirationTtl}`);
} else {
expect(query.has("expiration_ttl")).toBe(false);
}
return null;
}
);
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/api/form_data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function toMimeType(type: CfModuleType): string {
}
}

function toModule(module: CfModule, entryType?: CfModuleType): Blob {
function toModule(module: CfModule, entryType: CfModuleType): Blob {
const { type: moduleType, content } = module;
const type = toMimeType(moduleType ?? entryType);

Expand Down
12 changes: 4 additions & 8 deletions packages/wrangler/src/cfetch/internal.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fetch from "node-fetch";
import type { RequestInit, HeadersInit } from "node-fetch";
import fetch, { Headers } from "node-fetch";
import type { RequestInit } from "node-fetch";
import { getAPIToken, loginOrRefreshIfRequired } from "../user";

export const CF_API_BASE_URL =
Expand All @@ -21,7 +21,7 @@ export async function fetchInternal<ResponseType>(
): Promise<ResponseType> {
await requireLoggedIn();
const apiToken = requireApiToken();
const headers = cloneHeaders(init.headers);
const headers = new Headers(init.headers);
addAuthorizationHeader(headers, apiToken);

const queryString = queryParams ? `?${queryParams.toString()}` : "";
Expand Down Expand Up @@ -55,11 +55,7 @@ function requireApiToken(): string {
return apiToken;
}

function cloneHeaders(headers: HeadersInit): HeadersInit {
return { ...headers };
}

function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
function addAuthorizationHeader(headers: Headers, apiToken: string): void {
if (headers["Authorization"]) {
throw new Error(
"The request already specifies an authorisation header - cannot add a new one."
Expand Down
27 changes: 18 additions & 9 deletions packages/wrangler/src/kv.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ export interface NamespaceKeyInfo {
export async function listNamespaceKeys(
accountId: string,
namespaceId: string,
prefix?: string
prefix = ""
) {
return await fetchListResult<NamespaceKeyInfo>(
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`,
Expand All @@ -98,15 +98,20 @@ export async function putKeyValue(
value: string,
args?: { expiration?: number; expiration_ttl?: number }
) {
let searchParams: URLSearchParams | undefined;
if (args) {
searchParams = new URLSearchParams();
if (args.expiration) {
searchParams.set("expiration", `${args.expiration}`);
}
if (args.expiration_ttl) {
searchParams.set("expiration_ttl", `${args.expiration_ttl}`);
}
}
return await fetchResult(
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`,
{ method: "PUT", body: value },
args
? new URLSearchParams({
expiration: args.expiration?.toString(),
expiration_ttl: args.expiration_ttl?.toString(),
})
: undefined
searchParams
);
}

Expand Down Expand Up @@ -262,6 +267,10 @@ export function getNamespaceId({
/**
* KV namespace binding names must be valid JS identifiers.
*/
export function isValidNamespaceBinding(binding: string): boolean {
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding);
export function isValidNamespaceBinding(
binding: string | undefined
): binding is string {
return (
typeof binding === "string" && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding)
);
}
6 changes: 5 additions & 1 deletion packages/wrangler/src/sites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ export async function syncAssets(
);

const manifest = {};
const upload = [];
const upload: {
key: string;
value: string;
base64: boolean;
}[] = [];
// TODO: this can be more efficient by parallelising
for await (const file of getFilesInFolder(dirPath)) {
// TODO: "exclude:" config
Expand Down
18 changes: 10 additions & 8 deletions packages/wrangler/src/user.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -298,9 +298,9 @@ let initialised = false;

// we do this because we have some async stuff
// TODO: this should just happen in the top level
// abd we should fiure out how to do top level await
// and we should figure out how to do top level await
export async function initialise(): Promise<void> {
// get refreshtoken/accesstoken from fs if exists
// get refreshToken/accessToken from fs if exists
try {
// if CF_API_TOKEN available, use that
if (process.env.CF_API_TOKEN) {
Expand Down Expand Up @@ -350,7 +350,9 @@ export function getAPIToken(): string {
}

throwIfNotInitialised();
return LocalState.accessToken?.value;
// `throwIfNotInitialised()` ensures that the accessToken is guaranteed to be defined.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return LocalState.accessToken!.value;
}

interface AccessContext {
Expand Down Expand Up @@ -971,14 +973,14 @@ export async function getAccountId() {
});
} catch (err) {
// probably offline
return;
}
if (!response) return;
let accountId: string;
// @ts-expect-error need to type this response
const responseJSON: {

let accountId: string | undefined;
const responseJSON = (await response.json()) as {
success: boolean;
result: { id: string; account: { id: string; name: string } }[];
} = await response.json();
};

if (responseJSON.success === true) {
if (responseJSON.result.length === 1) {
Expand Down

0 comments on commit edc4b53

Please sign in to comment.