Skip to content

Make event params strongly typed #1155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Aug 22, 2022
25 changes: 25 additions & 0 deletions spec/common/metaprogramming.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// The MIT License (MIT)
//
// Copyright (c) 2022 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// This method will fail to compile if value is not of the explicit parameter type.
/* eslint-disable @typescript-eslint/no-unused-vars,@typescript-eslint/no-empty-function */
export function expectType<Type>(value: Type) {}
export function expectNever<Type extends never>() {}
99 changes: 99 additions & 0 deletions spec/common/params.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// The MIT License (MIT)
//
// Copyright (c) 2022 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE ignoreUnusedWarning OR OTHER DEALINGS IN THE
// SOFTWARE.

import { Extract, ParamsOf, Split } from "../../src/common/params";
import { expectNever, expectType } from "./metaprogramming";

describe("Params namespace", () => {
describe("Split", () => {
// Note the subtle difference in the first two cases:
// if passed a string (instead of a string literal) then split returns a
// string[], which means "any number of elements as long as they are a string"
// but if passed a literal string "" then split returns [] which means "a
// tuple of zero elements".

it("handles generic strings", () => {
expectType<Split<string, "/">>([] as string[]);
});

it("handles empty strings", () => {
expectType<Split<"", "/">>([]);
});

it("handles just a slash", () => {
expectType<Split<"/", "/">>([]);
});

it("handles literal strings with one component", () => {
expectType<Split<"a", "/">>(["a"]);
});

it("handles literal strings with more than one component", () => {
expectType<Split<"a/b/c", "/">>(["a", "b", "c"]);
});

it("strips leading slashes", () => {
expectType<Split<"/a/b/c", "/">>(["a", "b", "c"]);
});
});

describe("Extract", () => {
it("extracts nothing from strings without params", () => {
expectNever<Extract<"uid">>();
});

it("extracts {segment} captures", () => {
expectType<Extract<"{uid}">>("uid");
});

it("extracts {segment=*} captures", () => {
expectType<Extract<"{uid=*}">>("uid");
});

it("extracts {segment=**} captures", () => {
expectType<Extract<"{uid=**}">>("uid");
});
});

describe("ParamsOf", () => {
it("falls back to Record<string, string> without better type info", () => {
expectType<ParamsOf<string>>({} as Record<string, string>);
});

it("is the empty object when there are no params", () => {
expectType<ParamsOf<string>>({} as Record<string, never>);
});

it("extracts a single param", () => {
expectType<ParamsOf<"ignoreUnusedWarningrs/{uid}">>({
uid: "uid",
} as const);
});

it("extracts multiple params", () => {
expectType<ParamsOf<"ignoreUnusedWarningrs/{uid}/logs/{log=**}">>({
uid: "hello",
log: "world",
} as const);
});
});
});
49 changes: 49 additions & 0 deletions spec/v1/providers/database.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import * as config from '../../../src/common/config';
import { applyChange } from '../../../src/common/utilities/utils';
import * as functions from '../../../src/v1';
import * as database from '../../../src/v1/providers/database';
import { expectType } from '../../common/metaprogramming';

describe('Database Functions', () => {
describe('DatabaseBuilder', () => {
Expand Down Expand Up @@ -120,6 +121,18 @@ describe('Database Functions', () => {

return handler(event.data, event.context);
});

it('Should have params of the correct type', () => {
database.ref('foo').onWrite((event, context) => {
expectType<Record<string, never>>(context.params);
});
database.ref('foo/{bar}').onWrite((event, context) => {
expectType<{ bar: string }>(context.params);
});
database.ref('foo/{bar}/{baz}').onWrite((event, context) => {
expectType<{ bar: string; baz: string }>(context.params);
});
});
});

describe('#onCreate()', () => {
Expand Down Expand Up @@ -168,6 +181,18 @@ describe('Database Functions', () => {

return handler(event.data, event.context);
});

it('Should have params of the correct type', () => {
database.ref('foo').onCreate((event, context) => {
expectType<Record<string, never>>(context.params);
});
database.ref('foo/{bar}').onCreate((event, context) => {
expectType<{ bar: string }>(context.params);
});
database.ref('foo/{bar}/{baz}').onCreate((event, context) => {
expectType<{ bar: string; baz: string }>(context.params);
});
});
});

describe('#onUpdate()', () => {
Expand Down Expand Up @@ -216,6 +241,18 @@ describe('Database Functions', () => {

return handler(event.data, event.context);
});

it('Should have params of the correct type', () => {
database.ref('foo').onUpdate((event, context) => {
expectType<Record<string, never>>(context.params);
});
database.ref('foo/{bar}').onUpdate((event, context) => {
expectType<{ bar: string }>(context.params);
});
database.ref('foo/{bar}/{baz}').onUpdate((event, context) => {
expectType<{ bar: string; baz: string }>(context.params);
});
});
});

describe('#onDelete()', () => {
Expand Down Expand Up @@ -265,6 +302,18 @@ describe('Database Functions', () => {
return handler(event.data, event.context);
});
});

it('Should have params of the correct type', () => {
database.ref('foo').onDelete((event, context) => {
expectType<Record<string, never>>(context.params);
});
database.ref('foo/{bar}').onDelete((event, context) => {
expectType<{ bar: string }>(context.params);
});
database.ref('foo/{bar}/{baz}').onDelete((event, context) => {
expectType<{ bar: string; baz: string }>(context.params);
});
});
});

describe('handler namespace', () => {
Expand Down
17 changes: 13 additions & 4 deletions spec/v1/providers/firestore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { Timestamp } from 'firebase-admin/firestore';

import * as functions from '../../../src/v1';
import * as firestore from '../../../src/v1/providers/firestore';
import { expectType } from '../../common/metaprogramming';

describe('Firestore Functions', () => {
function constructValue(fields: any) {
Expand Down Expand Up @@ -117,7 +118,9 @@ describe('Firestore Functions', () => {
'projects/project1/databases/(default)/documents/users/{uid}';
const cloudFunction = firestore
.document('users/{uid}')
.onWrite(() => null);
.onWrite((snap, context) => {
expectType<{ uid: string }>(context.params);
});

expect(cloudFunction.__endpoint).to.deep.equal(
expectedEndpoint(resource, 'document.write')
Expand All @@ -130,7 +133,9 @@ describe('Firestore Functions', () => {
const cloudFunction = firestore
.namespace('v2')
.document('users/{uid}')
.onWrite(() => null);
.onWrite((snap, context) => {
expectType<{ uid: string }>(context.params);
});

expect(cloudFunction.__endpoint).to.deep.equal(
expectedEndpoint(resource, 'document.write')
Expand All @@ -156,7 +161,9 @@ describe('Firestore Functions', () => {
.database('myDB')
.namespace('v2')
.document('users/{uid}')
.onWrite(() => null);
.onWrite((snap, context) => {
expectType<{ uid: string }>(context.params);
});

expect(cloudFunction.__endpoint).to.deep.equal(
expectedEndpoint(resource, 'document.write')
Expand All @@ -171,7 +178,9 @@ describe('Firestore Functions', () => {
memory: '256MB',
})
.firestore.document('doc')
.onCreate((snap) => snap);
.onCreate((snap, context) => {
expectType<Record<string, string>>(context.params);
});

expect(fn.__endpoint.region).to.deep.equal(['us-east1']);
expect(fn.__endpoint.availableMemoryMb).to.deep.equal(256);
Expand Down
Loading