refactor: remove lodash

This commit is contained in:
moonrailgun 2024-08-16 00:22:24 +08:00
parent 22fc5f98f8
commit 49d0da3a6d
13 changed files with 40 additions and 52 deletions

View File

@ -501,9 +501,6 @@ importers:
jsonwebtoken: jsonwebtoken:
specifier: ^9.0.2 specifier: ^9.0.2
version: 9.0.2 version: 9.0.2
lodash:
specifier: ^4.17.21
version: 4.17.21
lodash-es: lodash-es:
specifier: ^4.17.21 specifier: ^4.17.21
version: 4.17.21 version: 4.17.21
@ -592,9 +589,6 @@ importers:
'@types/jsonwebtoken': '@types/jsonwebtoken':
specifier: ^9.0.5 specifier: ^9.0.5
version: 9.0.5 version: 9.0.5
'@types/lodash':
specifier: ^4.14.198
version: 4.14.198
'@types/lodash-es': '@types/lodash-es':
specifier: ^4.17.12 specifier: ^4.17.12
version: 4.17.12 version: 4.17.12

View File

@ -1,5 +1,5 @@
import { caching, MemoryCache } from 'cache-manager'; import { caching, MemoryCache } from 'cache-manager';
import _ from 'lodash'; import { uniqueId } from 'lodash-es';
let _cacheManager: MemoryCache; let _cacheManager: MemoryCache;
export async function getCacheManager() { export async function getCacheManager() {
@ -20,7 +20,7 @@ export async function getCacheManager() {
export function buildQueryWithCache<T, Args extends any[]>( export function buildQueryWithCache<T, Args extends any[]>(
fetchFn: (...args: Args) => Promise<T> fetchFn: (...args: Args) => Promise<T>
) { ) {
const id = _.uniqueId('cache-query'); const id = uniqueId('cache-query');
const get = async (...args: Args): Promise<T> => { const get = async (...args: Args): Promise<T> => {
const key = [id, ...args.map((a) => JSON.stringify(a))].join('|'); const key = [id, ...args.map((a) => JSON.stringify(a))].join('|');

View File

@ -6,9 +6,9 @@ import { FeedChannelNotifyFrequency, Prisma } from '@prisma/client';
import { env } from '../utils/env.js'; import { env } from '../utils/env.js';
import { sendNotification } from '../model/notification/index.js'; import { sendNotification } from '../model/notification/index.js';
import { token } from '../model/notification/token/index.js'; import { token } from '../model/notification/token/index.js';
import _ from 'lodash';
import pMap from 'p-map'; import pMap from 'p-map';
import { sendFeedEventsNotify } from '../model/feed/event.js'; import { sendFeedEventsNotify } from '../model/feed/event.js';
import { get } from 'lodash-es';
type WebsiteEventCountSqlReturn = { type WebsiteEventCountSqlReturn = {
workspace_id: string; workspace_id: string;
@ -368,7 +368,7 @@ async function dailyHTTPCertCheckNotify() {
continue; continue;
} }
const content = `[${m.name}][${_.get(m.payload, 'url')}] Certificate will be expired in ${daysRemaining} days`; const content = `[${m.name}][${get(m.payload, 'url')}] Certificate will be expired in ${daysRemaining} days`;
try { try {
await sendNotification(n, content, [token.text(content)]).catch( await sendNotification(n, content, [token.text(content)]).catch(

View File

@ -17,9 +17,9 @@ import { createTransport } from 'nodemailer';
import { Theme } from '@auth/core/types'; import { Theme } from '@auth/core/types';
import { generateSMTPHTML } from '../utils/smtp.js'; import { generateSMTPHTML } from '../utils/smtp.js';
import { SYSTEM_ROLES } from '@tianji/shared'; import { SYSTEM_ROLES } from '@tianji/shared';
import _ from 'lodash';
import { IncomingMessage } from 'http'; import { IncomingMessage } from 'http';
import { type Session } from '@auth/express'; import { type Session } from '@auth/express';
import { compact, set } from 'lodash-es';
export interface UserAuthPayload { export interface UserAuthPayload {
id: string; id: string;
@ -31,7 +31,7 @@ export const authConfig: Omit<AuthConfig, 'raw'> = {
debug: env.isProd ? false : true, debug: env.isProd ? false : true,
basePath: '/api/auth', basePath: '/api/auth',
trustHost: true, trustHost: true,
providers: _.compact([ providers: compact([
Credentials({ Credentials({
id: 'account', id: 'account',
name: 'Account', name: 'Account',
@ -103,8 +103,8 @@ export const authConfig: Omit<AuthConfig, 'raw'> = {
}; };
}, },
session({ session, token, user }) { session({ session, token, user }) {
_.set(session, ['user', 'id'], token.sub); set(session, ['user', 'id'], token.sub);
_.set(session, ['user', 'role'], token.role); set(session, ['user', 'role'], token.role);
return session; return session;
}, },

View File

@ -2,7 +2,6 @@ import { z } from 'zod';
import { MonitorProvider } from './type.js'; import { MonitorProvider } from './type.js';
import axios from 'axios'; import axios from 'axios';
import { saveMonitorStatus } from './_utils.js'; import { saveMonitorStatus } from './_utils.js';
import _ from 'lodash';
const openaiCreditGrantsSchema = z.object({ const openaiCreditGrantsSchema = z.object({
object: z.string(), object: z.string(),

View File

@ -1,6 +1,5 @@
import { ServerStatusInfo } from '../../types/index.js'; import { ServerStatusInfo } from '../../types/index.js';
import { createSubscribeInitializer, subscribeEventBus } from '../ws/shared.js'; import { createSubscribeInitializer, subscribeEventBus } from '../ws/shared.js';
import _ from 'lodash';
import { isServerOnline } from '@tianji/shared'; import { isServerOnline } from '@tianji/shared';
const serverMap: Record< const serverMap: Record<

View File

@ -50,7 +50,6 @@
"is-localhost-ip": "^2.0.0", "is-localhost-ip": "^2.0.0",
"isolated-vm": "^4.7.2", "isolated-vm": "^4.7.2",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"lodash": "^4.17.21",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"maxmind": "^4.3.18", "maxmind": "^4.3.18",
"md5": "^2.3.0", "md5": "^2.3.0",
@ -82,7 +81,6 @@
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
"@types/fs-extra": "^11.0.3", "@types/fs-extra": "^11.0.3",
"@types/jsonwebtoken": "^9.0.5", "@types/jsonwebtoken": "^9.0.5",
"@types/lodash": "^4.14.198",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"@types/md5": "^2.3.5", "@types/md5": "^2.3.5",
"@types/morgan": "^1.9.5", "@types/morgan": "^1.9.5",

View File

@ -13,7 +13,6 @@ import {
FeedEventModelSchema, FeedEventModelSchema,
} from '../../../prisma/zod/index.js'; } from '../../../prisma/zod/index.js';
import { prisma } from '../../../model/_client.js'; import { prisma } from '../../../model/_client.js';
import _ from 'lodash';
import { import {
buildFeedPublicOpenapi, buildFeedPublicOpenapi,
feedIntegrationRouter, feedIntegrationRouter,

View File

@ -1,12 +1,12 @@
import { z } from 'zod'; import { z } from 'zod';
import { OpenApiMetaInfo, publicProcedure, router } from '../../trpc.js'; import { OpenApiMetaInfo, publicProcedure, router } from '../../trpc.js';
import { prisma } from '../../../model/_client.js'; import { prisma } from '../../../model/_client.js';
import _ from 'lodash';
import { OpenApiMeta } from 'trpc-openapi'; import { OpenApiMeta } from 'trpc-openapi';
import { OPENAPI_TAG } from '../../../utils/const.js'; import { OPENAPI_TAG } from '../../../utils/const.js';
import { createFeedEvent } from '../../../model/feed/event.js'; import { createFeedEvent } from '../../../model/feed/event.js';
import { tencentCloudAlarmSchema } from '../../../model/_schema/feed.js'; import { tencentCloudAlarmSchema } from '../../../model/_schema/feed.js';
import { logger } from '../../../utils/logger.js'; import { logger } from '../../../utils/logger.js';
import { get, map } from 'lodash-es';
export const feedIntegrationRouter = router({ export const feedIntegrationRouter = router({
github: publicProcedure github: publicProcedure
@ -45,17 +45,17 @@ export const feedIntegrationRouter = router({
} }
if (eventType === 'push') { if (eventType === 'push') {
const pusherName = _.get(data, 'pusher.name'); const pusherName = get(data, 'pusher.name');
const pusherEmail = _.get(data, 'pusher.email'); const pusherEmail = get(data, 'pusher.email');
const commits = _.map(_.get(data, 'commits') as any[], (val) => const commits = map(get(data, 'commits') as any[], (val) =>
String(val.id).substring(0, 9) String(val.id).substring(0, 9)
).join(', '); ).join(', ');
const fullName = _.get(data, 'repository.full_name'); const fullName = get(data, 'repository.full_name');
const repoUrl = _.get(data, 'repository.html_url'); const repoUrl = get(data, 'repository.html_url');
const ref = String(_.get(data, 'ref')); const ref = String(get(data, 'ref'));
const senderId = String(_.get(data, 'sender.id')); const senderId = String(get(data, 'sender.id'));
const senderName = String(_.get(data, 'sender.login')); const senderName = String(get(data, 'sender.login'));
const url = String(_.get(data, 'compare')); const url = String(get(data, 'compare'));
await createFeedEvent(workspaceId, { await createFeedEvent(workspaceId, {
channelId: channelId, channelId: channelId,
@ -71,13 +71,13 @@ export const feedIntegrationRouter = router({
return 'ok'; return 'ok';
} else if (eventType === 'star') { } else if (eventType === 'star') {
const starCount = _.get(data, 'repository.stargazers_count'); const starCount = get(data, 'repository.stargazers_count');
const fullName = _.get(data, 'repository.full_name'); const fullName = get(data, 'repository.full_name');
const repoUrl = _.get(data, 'repository.html_url'); const repoUrl = get(data, 'repository.html_url');
const senderId = String(_.get(data, 'sender.id')); const senderId = String(get(data, 'sender.id'));
const senderName = String(_.get(data, 'sender.login')); const senderName = String(get(data, 'sender.login'));
const senderUrl = String(_.get(data, 'sender.html_url')); const senderUrl = String(get(data, 'sender.html_url'));
const url = String(_.get(data, 'compare')); const url = String(get(data, 'compare'));
await createFeedEvent(workspaceId, { await createFeedEvent(workspaceId, {
channelId: channelId, channelId: channelId,
@ -93,14 +93,14 @@ export const feedIntegrationRouter = router({
return 'ok'; return 'ok';
} else if (eventType === 'issues') { } else if (eventType === 'issues') {
const action = _.get(data, 'action') as 'opened' | 'closed'; const action = get(data, 'action') as 'opened' | 'closed';
const starCount = _.get(data, 'repository.stargazers_count'); const starCount = get(data, 'repository.stargazers_count');
const fullName = _.get(data, 'repository.full_name'); const fullName = get(data, 'repository.full_name');
const repoUrl = _.get(data, 'repository.html_url'); const repoUrl = get(data, 'repository.html_url');
const senderId = String(_.get(data, 'sender.id')); const senderId = String(get(data, 'sender.id'));
const senderName = String(_.get(data, 'sender.login')); const senderName = String(get(data, 'sender.login'));
const url = String(_.get(data, 'issue.url')); const url = String(get(data, 'issue.url'));
const title = String(_.get(data, 'issue.title')); const title = String(get(data, 'issue.title'));
let eventName = eventType; let eventName = eventType;
let eventContent = ''; let eventContent = '';

View File

@ -1,5 +1,4 @@
import { initTRPC, inferAsyncReturnType, TRPCError } from '@trpc/server'; import { initTRPC, inferAsyncReturnType, TRPCError } from '@trpc/server';
import _ from 'lodash';
import { z } from 'zod'; import { z } from 'zod';
import { jwtVerify } from '../middleware/auth.js'; import { jwtVerify } from '../middleware/auth.js';
import { getWorkspaceUser } from '../model/workspace.js'; import { getWorkspaceUser } from '../model/workspace.js';
@ -8,6 +7,7 @@ import type { Request } from 'express';
import { OpenApiMeta } from 'trpc-openapi'; import { OpenApiMeta } from 'trpc-openapi';
import { getSession } from '@auth/express'; import { getSession } from '@auth/express';
import { authConfig } from '../model/auth.js'; import { authConfig } from '../model/auth.js';
import { get } from 'lodash-es';
export async function createContext({ req }: { req: Request }) { export async function createContext({ req }: { req: Request }) {
const authorization = req.headers['authorization'] ?? ''; const authorization = req.headers['authorization'] ?? '';
@ -97,7 +97,7 @@ function createWorkspacePermissionMiddleware(roles: ROLES[] = []) {
return isUser.unstable_pipe(async (opts) => { return isUser.unstable_pipe(async (opts) => {
const { ctx, input } = opts; const { ctx, input } = opts;
const workspaceId = _.get(input, 'workspaceId', ''); const workspaceId = get(input, 'workspaceId', '');
if (!workspaceId) { if (!workspaceId) {
throw new TRPCError({ throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR', code: 'INTERNAL_SERVER_ERROR',

View File

@ -5,7 +5,6 @@ import { DynamicDataType } from './types.js';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import minMax from 'dayjs/plugin/minMax.js'; import minMax from 'dayjs/plugin/minMax.js';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import _ from 'lodash';
import { getWorkspaceWebsiteDateRange } from '../model/workspace.js'; import { getWorkspaceWebsiteDateRange } from '../model/workspace.js';
import { isCuid } from '@paralleldrive/cuid2'; import { isCuid } from '@paralleldrive/cuid2';
import { getMinimumUnit } from '@tianji/shared'; import { getMinimumUnit } from '@tianji/shared';

View File

@ -1,6 +1,6 @@
import { v1 as uuid } from 'uuid'; import { v1 as uuid } from 'uuid';
import md5 from 'md5'; import md5 from 'md5';
import _ from 'lodash'; import { compact } from 'lodash-es';
const jwtSecret = const jwtSecret =
!process.env.JWT_SECRET || !process.env.JWT_SECRET ||
@ -14,7 +14,7 @@ export const env = {
jwtSecret, jwtSecret,
port: Number(process.env.PORT || 12345), port: Number(process.env.PORT || 12345),
auth: { auth: {
provider: _.compact([ provider: compact([
!!process.env.EMAIL_SERVER && 'email', !!process.env.EMAIL_SERVER && 'email',
!!process.env.AUTH_GITHUB_ID && 'github', !!process.env.AUTH_GITHUB_ID && 'github',
!!process.env.AUTH_GOOGLE_ID && 'google', !!process.env.AUTH_GOOGLE_ID && 'google',

View File

@ -1,10 +1,10 @@
import { Prisma } from '@prisma/client'; import { Prisma } from '@prisma/client';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import _ from 'lodash';
import { loadWebsite } from '../model/website.js'; import { loadWebsite } from '../model/website.js';
import { maxDate } from './common.js'; import { maxDate } from './common.js';
import { FILTER_COLUMNS, OPERATORS, SESSION_COLUMNS } from './const.js'; import { FILTER_COLUMNS, OPERATORS, SESSION_COLUMNS } from './const.js';
import { loadTelemetry } from '../model/telemetry.js'; import { loadTelemetry } from '../model/telemetry.js';
import { get } from 'lodash-es';
const POSTGRESQL_DATE_FORMATS = { const POSTGRESQL_DATE_FORMATS = {
minute: 'YYYY-MM-DD HH24:MI:00', minute: 'YYYY-MM-DD HH24:MI:00',
@ -136,7 +136,7 @@ export function getWebsiteFilterQuery(
const query = Object.keys(filters).reduce<string[]>((arr, name) => { const query = Object.keys(filters).reduce<string[]>((arr, name) => {
const value: any = filters[name as keyof WebsiteQueryFilters]; const value: any = filters[name as keyof WebsiteQueryFilters];
const operator = value?.filter ?? OPERATORS.equals; const operator = value?.filter ?? OPERATORS.equals;
const column = _.get(FILTER_COLUMNS, name, options?.columns?.[name]); const column = get(FILTER_COLUMNS, name, options?.columns?.[name]);
// TODO // TODO
@ -163,7 +163,7 @@ export function getTelemetryFilterQuery(
const query = Object.keys(filters).reduce<string[]>((arr, name) => { const query = Object.keys(filters).reduce<string[]>((arr, name) => {
const value: any = filters[name as keyof BaseQueryFilters]; const value: any = filters[name as keyof BaseQueryFilters];
const operator = value?.filter ?? OPERATORS.equals; const operator = value?.filter ?? OPERATORS.equals;
const column = _.get(FILTER_COLUMNS, name, options?.columns?.[name]); const column = get(FILTER_COLUMNS, name, options?.columns?.[name]);
// TODO // TODO