Skip to content

Commit

Permalink
remove more lodash functions - sortBy, assign, etc (#4670)
Browse files Browse the repository at this point in the history
* remove more lodash functions - sortBy, assign, etc

* removing more lodash

* remove logging

* remove unused import

Co-authored-by: joehan <joehanley@google.com>
  • Loading branch information
bkendall and joehan authored Jun 20, 2022
1 parent 76d0593 commit faeba42
Show file tree
Hide file tree
Showing 15 changed files with 35 additions and 44 deletions.
7 changes: 4 additions & 3 deletions src/accountImporter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as clc from "cli-color";
import * as _ from "lodash";

import { Client } from "./apiv2";
import { googleOrigin } from "./api";
Expand Down Expand Up @@ -260,7 +259,9 @@ function validateProviderUserInfo(providerUserInfo: { providerId: string; error?
error: JSON.stringify(providerUserInfo, null, 2) + " has unsupported providerId",
};
}
const keydiff = _.difference(Object.keys(providerUserInfo), ALLOWED_PROVIDER_USER_INFO_KEYS);
const keydiff = Object.keys(providerUserInfo).filter(
(k) => !ALLOWED_PROVIDER_USER_INFO_KEYS.includes(k)
);
if (keydiff.length) {
return {
error:
Expand All @@ -271,7 +272,7 @@ function validateProviderUserInfo(providerUserInfo: { providerId: string; error?
}

export function validateUserJson(userJson: any): { error?: string } {
const keydiff = _.difference(Object.keys(userJson), ALLOWED_JSON_KEYS);
const keydiff = Object.keys(userJson).filter((k) => !ALLOWED_JSON_KEYS.includes(k));
if (keydiff.length) {
return {
error: JSON.stringify(userJson, null, 2) + " has unsupported keys: " + keydiff.join(","),
Expand Down
7 changes: 3 additions & 4 deletions src/commands/database-push.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as _ from "lodash";
import * as clc from "cli-color";
import * as fs from "fs";

Expand Down Expand Up @@ -26,8 +25,8 @@ export const command = new Command("database:push <path> [infile]")
.before(requireDatabaseInstance)
.before(populateInstanceDetails)
.before(printNoticeIfEmulated, Emulators.DATABASE)
.action(async (path, infile, options) => {
if (!_.startsWith(path, "/")) {
.action(async (path: string, infile, options) => {
if (!path.startsWith("/")) {
throw new FirebaseError("Path must begin with /");
}
const inStream =
Expand All @@ -53,7 +52,7 @@ export const command = new Command("database:push <path> [infile]")
throw new FirebaseError(`Unexpected error while pushing data: ${err}`, { exit: 2 });
}

if (!_.endsWith(path, "/")) {
if (!path.endsWith("/")) {
path += "/";
}

Expand Down
5 changes: 2 additions & 3 deletions src/commands/database-remove.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { realtimeOriginOrEmulatorOrCustomUrl } from "../database/api";
import * as utils from "../utils";
import { promptOnce } from "../prompt";
import * as clc from "cli-color";
import * as _ from "lodash";

export const command = new Command("database:remove <path>")
.description("remove data from your Firebase at the specified path")
Expand All @@ -22,8 +21,8 @@ export const command = new Command("database:remove <path>")
.before(requireDatabaseInstance)
.before(populateInstanceDetails)
.before(warnEmulatorNotSupported, Emulators.DATABASE)
.action(async (path, options) => {
if (!_.startsWith(path, "/")) {
.action(async (path: string, options) => {
if (!path.startsWith("/")) {
return utils.reject("Path must begin with /", { exit: 1 });
}
const origin = realtimeOriginOrEmulatorOrCustomUrl(options.instanceDetails.databaseUrl);
Expand Down
5 changes: 2 additions & 3 deletions src/commands/database-set.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as _ from "lodash";
import * as clc from "cli-color";
import * as fs from "fs";

Expand Down Expand Up @@ -28,8 +27,8 @@ export const command = new Command("database:set <path> [infile]")
.before(requireDatabaseInstance)
.before(populateInstanceDetails)
.before(printNoticeIfEmulated, Emulators.DATABASE)
.action(async (path, infile, options) => {
if (!_.startsWith(path, "/")) {
.action(async (path: string, infile, options) => {
if (!path.startsWith("/")) {
throw new FirebaseError("Path must begin with /");
}
const origin = realtimeOriginOrEmulatorOrCustomUrl(options.instanceDetails.databaseUrl);
Expand Down
5 changes: 3 additions & 2 deletions src/commands/ext-dev-list.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as clc from "cli-color";
import Table = require("cli-table");
import * as _ from "lodash";

import { Command } from "../command";
import { FirebaseError } from "../error";
Expand Down Expand Up @@ -41,7 +40,9 @@ export const command = new Command("ext:dev:list <publisherId>")
style: { head: ["yellow"] },
});
// Order extensions newest to oldest.
const sorted = _.sortBy(extensions, "createTime", "asc").reverse();
const sorted = extensions.sort(
(a, b) => new Date(b.createTime).valueOf() - new Date(a.createTime).valueOf()
);
sorted.forEach((extension) => {
table.push([
last(extension.ref.split("/")),
Expand Down
5 changes: 2 additions & 3 deletions src/commands/open.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as _ from "lodash";
import * as clc from "cli-color";
import * as open from "open";

Expand Down Expand Up @@ -56,7 +55,7 @@ export const command = new Command("open [link]")
.before(requirePermissions)
.before(requireDatabaseInstance)
.action(async (linkName: string, options: any): Promise<void> => {
let link = _.find(LINKS, { arg: linkName });
let link = LINKS.find((l) => l.arg === linkName);
if (linkName && !link) {
throw new FirebaseError(
"Unrecognized link name. Valid links are:\n\n" + LINKS.map((l) => l.arg).join("\n")
Expand All @@ -69,7 +68,7 @@ export const command = new Command("open [link]")
message: "What link would you like to open?",
choices: CHOICES,
});
link = _.find(LINKS, { name });
link = LINKS.find((l) => l.name === name);
}
if (!link) {
throw new FirebaseError(
Expand Down
11 changes: 3 additions & 8 deletions src/commands/serve.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import * as clc from "cli-color";
import * as _ from "lodash";

import { Command } from "../command";
import { logger } from "../logger";
Expand All @@ -13,18 +12,14 @@ import { FirebaseError } from "../error";

const VALID_TARGETS = ["hosting", "functions"];
const REQUIRES_AUTH = ["hosting", "functions"];
const ALL_TARGETS = _.union(VALID_TARGETS, ["database", "firestore"]);
const ALL_TARGETS = Array.from(new Set(["database", "firestore", ...VALID_TARGETS]));

function filterOnly(list: string[], only = ""): string[] {
if (!only) {
return [];
}
return _.intersection(
list,
only.split(",").map((opt) => {
return opt.split(":")[0];
})
);
const targets = only.split(",").map((o) => o.split(":")[0]);
return targets.filter((t) => list.includes(t));
}

export const command = new Command("serve")
Expand Down
2 changes: 1 addition & 1 deletion src/deploy/lifecycleHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ function getChildEnvironment(target: string, overallOptions: any, config: any) {
}

// Copying over environment variables
return _.assign({}, process.env, {
return Object.assign({}, process.env, {
GCLOUD_PROJECT: projectId,
PROJECT_DIR: projectDir,
RESOURCE_DIR: resourceDir,
Expand Down
2 changes: 1 addition & 1 deletion src/deploy/storage/prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export default async function (context: any, options: Options): Promise<void> {

if (_.isPlainObject(rulesConfig)) {
const defaultBucket = await gcp.storage.getDefaultBucket(options.project);
rulesConfig = [_.assign(rulesConfig, { bucket: defaultBucket })];
rulesConfig = [Object.assign(rulesConfig, { bucket: defaultBucket })];
_.set(context, "storage.rules", rulesConfig);
}

Expand Down
5 changes: 2 additions & 3 deletions src/emulator/controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as _ from "lodash";
import * as clc from "cli-color";
import * as fs from "fs";
import * as path from "path";
Expand Down Expand Up @@ -205,7 +204,7 @@ export function filterEmulatorTargets(options: any): Emulators[] {
const only = onlyOptions.split(",").map((o) => {
return o.split(":")[0];
});
targets = _.intersection(targets, only as Emulators[]);
targets = targets.filter((t) => only.includes(t));
}

return targets;
Expand Down Expand Up @@ -380,7 +379,7 @@ export async function startAll(
const requested: string[] = onlyOptions.split(",").map((o) => {
return o.split(":")[0];
});
const ignored = _.difference(requested, targets);
const ignored = requested.filter((k) => !targets.includes(k as Emulators));

for (const name of ignored) {
if (isEmulator(name)) {
Expand Down
4 changes: 1 addition & 3 deletions src/extensions/askUserForParam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,8 +372,6 @@ async function addNewSecretVersion(
}

export function getInquirerDefault(options: ParamOption[], def: string): string {
const defaultOption = _.find(options, (option) => {
return option.value === def;
});
const defaultOption = options.find((o) => o.value === def);
return defaultOption ? defaultOption.label || defaultOption.value : "";
}
13 changes: 7 additions & 6 deletions src/extensions/listExtensions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as _ from "lodash";
import * as clc from "cli-color";
import Table = require("cli-table");

Expand All @@ -13,7 +12,7 @@ import * as extensionsUtils from "./utils";
* @param projectId ID of the project we're querying
* @return mapping that contains a list of instances under the "instances" key
*/
export async function listExtensions(projectId: string): Promise<any> {
export async function listExtensions(projectId: string): Promise<Record<string, string>[]> {
const instances = await listInstances(projectId);
if (instances.length < 1) {
logLabeledBullet(
Expand All @@ -28,21 +27,23 @@ export async function listExtensions(projectId: string): Promise<any> {
style: { head: ["yellow"] },
});
// Order instances newest to oldest.
const sorted = _.sortBy(instances, "createTime", "asc").reverse();
const sorted = instances.sort(
(a, b) => new Date(b.createTime).valueOf() - new Date(a.createTime).valueOf()
);
const formatted: Record<string, string>[] = [];
sorted.forEach((instance) => {
let extension = _.get(instance, "config.extensionRef", "");
let extension = instance.config.extensionRef || "";
let publisher;
if (extension === "") {
extension = _.get(instance, "config.source.spec.name", "");
extension = instance.config.source.spec.name || "";
publisher = "N/A";
} else {
publisher = extension.split("/")[0];
}
const instanceId = last(instance.name.split("/")) ?? "";
const state =
instance.state +
(_.get(instance, "config.source.state", "ACTIVE") === "DELETED" ? " (UNPUBLISHED)" : "");
((instance.config.source.state || "ACTIVE") === "DELETED" ? " (UNPUBLISHED)" : "");
const version = instance?.config?.source?.spec?.version;
const updateTime = extensionsUtils.formatTimestamp(instance.updateTime);
table.push([extension, publisher, instanceId, state, version, updateTime]);
Expand Down
4 changes: 2 additions & 2 deletions src/functionsConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export async function setVariablesRecursive(
val: string | { [key: string]: any }
): Promise<any> {
let parsed = val;
if (_.isString(val)) {
if (typeof val === "string") {
try {
// Only attempt to parse 'val' if it is a String (takes care of unparsed JSON, numbers, quoted string, etc.)
parsed = JSON.parse(val);
Expand Down Expand Up @@ -186,7 +186,7 @@ export function parseUnsetArgs(args: string[]): ParsedArg[] {
const parsed: ParsedArg[] = [];
let splitArgs: string[] = [];
for (const arg of args) {
splitArgs = _.union(splitArgs, arg.split(","));
splitArgs = Array.from(new Set([...splitArgs, ...arg.split(",")]));
}

for (const key of splitArgs) {
Expand Down
2 changes: 1 addition & 1 deletion src/gcp/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export async function getLatestRulesetName(
): Promise<string | null> {
const releases = await listAllReleases(projectId);
const prefix = `projects/${projectId}/releases/${service}`;
const release = _.find(releases, (r) => r.name.startsWith(prefix));
const release = releases.find((r) => r.name.startsWith(prefix));

if (!release) {
return null;
Expand Down
2 changes: 1 addition & 1 deletion src/test/emulators/auth/setAccountInfo.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ describeAuthEmulator("accounts:update", ({ authApi, getClock }) => {
const { localId, idToken } = await registerUser(authApi(), user);
const savedUserInfo = await getAccountInfoByIdToken(authApi(), idToken);
expect(savedUserInfo.mfaInfo).to.have.length(2);
const oldEnrollmentIds = savedUserInfo.mfaInfo!.map((_) => _.mfaEnrollmentId);
const oldEnrollmentIds = savedUserInfo.mfaInfo!.map((info) => info.mfaEnrollmentId);

const newMfaInfo = {
displayName: "New New",
Expand Down

0 comments on commit faeba42

Please sign in to comment.