Skip to content

Commit

Permalink
refactor: general refactors (#1228)
Browse files Browse the repository at this point in the history
* chore: queue top voters airdrop WIP

* refactor: simplify expressions, reorganize imports, etc

* refactor: add await to async function calls

* refactor: remove unused grant category conversion

* refactor: add missing dependency used in postcss.config.js

* refactor: update for catalyst deprecated methods

* refactor: update deprecated methods, remove unused method

* refactor: update queries with namedQuery

* refactor: remove unnecessary generic type arguments

* refactor: update proposals query methods

* fix: rebasing error
  • Loading branch information
1emu committed Sep 6, 2023
1 parent 0434920 commit 1ce25b8
Show file tree
Hide file tree
Showing 21 changed files with 2,125 additions and 2,436 deletions.
4,441 changes: 2,075 additions & 2,366 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"classnames": "^2.3.2",
"clipboard-copy": "^4.0.1",
"core-js": "^3.21.1",
"cssnano": "^6.0.1",
"dayjs-precise-range": "^1.0.1",
"dcl-catalyst-client": "^21.5.0",
"decentraland-gatsby": "^5.75.1",
Expand Down
4 changes: 2 additions & 2 deletions src/back/routes/coauthor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import validate from 'decentraland-gatsby/dist/entities/Route/validate'
import schema from 'decentraland-gatsby/dist/entities/Schema'
import { Request } from 'express'

import { validateAddress } from '../../back/utils/validations'
import CoauthorModel from '../../entities/Coauthor/model'
import {
CoauthorAttributes,
Expand All @@ -19,6 +18,7 @@ import {
import { isCoauthoringUpdatable } from '../../entities/Coauthor/utils'
import ProposalModel from '../../entities/Proposal/model'
import { ProposalAttributes } from '../../entities/Proposal/types'
import { validateAddress } from '../utils/validations'

export default routes((route) => {
const withAuth = auth()
Expand Down Expand Up @@ -60,7 +60,7 @@ export async function getCoauthors(req: Request) {

const updateStatusValidator = schema.compile(updateStatusScheme)

export async function updateStatus(req: WithAuth<Request>): Promise<CoauthorAttributes> {
export async function updateStatus(req: WithAuth): Promise<CoauthorAttributes> {
const user = req.auth!
const id = req.params.proposal
const data = validate<UpdateStatus>(updateStatusValidator, req.body || {})
Expand Down
2 changes: 1 addition & 1 deletion src/back/routes/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ async function updateProposalUpdate(req: WithAuth<Request<{ proposal: string }>>
const updatedUpdate = await UpdateService.getById(id)
if (updatedUpdate) {
if (!completion_date) {
DiscourseService.createUpdate(updatedUpdate, proposal.title)
await DiscourseService.createUpdate(updatedUpdate, proposal.title)
DiscordService.newUpdate(proposal.id, proposal.title, update.id, user)
} else {
UpdateService.commentUpdateEditInDiscourse(updatedUpdate)
Expand Down
2 changes: 1 addition & 1 deletion src/components/Common/Typography/Link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { navigate } from '../../../utils/locations'
import './Link.css'

function isMetaClick(event: React.MouseEvent<HTMLAnchorElement>) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)
return event.metaKey || event.altKey || event.ctrlKey || event.shiftKey
}

type Props = React.AnchorHTMLAttributes<HTMLAnchorElement>
Expand Down
4 changes: 2 additions & 2 deletions src/components/Proposal/ProposalHeaderPoi.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export default function ProposalHeaderPoi({ configuration }: Props) {
const { x, y } = configuration

const fetchSceneImg = async (x: number, y: number) => {
const scenes = await Catalyst.get().getEntityScenes([[x, y]])
const scenes = await Catalyst.getInstance().getEntityScenes([[x, y]])
const scene = scenes[0]
if (!scene) {
return null
Expand All @@ -32,7 +32,7 @@ export default function ProposalHeaderPoi({ configuration }: Props) {
const list = scene.content || []
const content = list.find((content) => content.file === image)
if (content) {
image = Catalyst.get().getContentUrl(content.hash)
image = Catalyst.getInstance().getContentUrl(content.hash)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ interface ExtendedController extends React.ComponentProps<typeof Controller> {
loading?: boolean
disabled?: boolean
error?: boolean
control: Control<any, any>
control: Control<any>
onOptionClick?: (event: React.MouseEvent<HTMLDivElement>, data: DropdownItemProps) => void
}

Expand Down
6 changes: 3 additions & 3 deletions src/components/Proposal/Submit/ProposalSubmitCatalystPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ export default function ProposalSubmitCatalystPage({ catalystType }: Props) {

const { isLoading: isCommsStatusLoading, isError: isErrorOnCommsStatus } = useQuery({
queryKey: [`commsStatus#${domain}`],
queryFn: () => (domain ? Catalyst.from('https://' + domain).getCommsStatus() : null),
queryFn: () => (domain ? Catalyst.getInstanceFrom('https://' + domain).getCommsStatus() : null),
})
const { isLoading: isContentStatusLoading, isError: isErrorOnContentStatus } = useQuery({
queryKey: [`contentStatus#${domain}`],
queryFn: () => (domain ? Catalyst.from('https://' + domain).getContentStatus() : null),
queryFn: () => (domain ? Catalyst.getInstanceFrom('https://' + domain).getContentStatus() : null),
})
const { isLoading: isLambdasStatusLoading, isError: isErrorOnLambdasStatus } = useQuery({
queryKey: [`lambdasStatus#${domain}`],
queryFn: () => (domain ? Catalyst.from('https://' + domain).getLambdasStatus() : null),
queryFn: () => (domain ? Catalyst.getInstanceFrom('https://' + domain).getLambdasStatus() : null),
})

const [formDisabled, setFormDisabled] = useState(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function getContestingProposalsItems(
value: contestant.size,
className: isOverBudget ? 'CompetingProposalOverbudgetBar' : 'CompetingProposalBudgetBar',
selected: highlightedContestant === contestant.id,
onHover: (e: React.MouseEvent<unknown>) => {
onHover: () => {
setHighlightedContestant(contestant.id)
},
onBlur: () => {
Expand Down
4 changes: 2 additions & 2 deletions src/entities/Coauthor/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default class CoauthorModel extends Model<CoauthorAttributes> {
WHERE lower(${columns([columnName])}) = lower(${value})
${conditional(!!status, SQL` AND "status" = ${status}`)}
`
return await this.query(query)
return await this.namedQuery('find_coauthor_by_column', query)
}

static async findCoauthors(proposalId: string, status?: CoauthorStatus): Promise<CoauthorAttributes[]> {
Expand All @@ -41,7 +41,7 @@ export default class CoauthorModel extends Model<CoauthorAttributes> {
VALUES
${objectValues(cols, coauthors)}
`
await this.query(query)
await this.namedQuery('create_multiple', query)
}

static async findAllByProposals(proposals: ProposalAttributes[], status?: CoauthorStatus): Promise<string[]> {
Expand Down
24 changes: 1 addition & 23 deletions src/entities/Grant/utils.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,11 @@
import toSnakeCase from 'lodash/snakeCase'

import Accelerator from '../../components/Icon/Grants/Accelerator'
import CoreUnit from '../../components/Icon/Grants/CoreUnit'
import Documentation from '../../components/Icon/Grants/Documentation'
import InWorldContent from '../../components/Icon/Grants/InWorldContent'
import Platform from '../../components/Icon/Grants/Platform'
import SocialMediaContent from '../../components/Icon/Grants/SocialMediaContent'
import Sponsorship from '../../components/Icon/Grants/Sponsorship'

import {
GRANT_PROPOSAL_MAX_BUDGET,
GRANT_PROPOSAL_MIN_BUDGET,
NewGrantCategory,
OldGrantCategory,
ProjectStatus,
ProposalGrantCategory,
} from './types'
import { GRANT_PROPOSAL_MAX_BUDGET, GRANT_PROPOSAL_MIN_BUDGET, ProjectStatus } from './types'

export const isValidGrantBudget = (size: number) => {
return !(size < GRANT_PROPOSAL_MIN_BUDGET || size > GRANT_PROPOSAL_MAX_BUDGET)
}

export function toProposalGrantCategory(category?: string | null): ProposalGrantCategory | null {
const categories = [...Object.values(NewGrantCategory), ...Object.values(OldGrantCategory)]
const index = categories.map(toSnakeCase).indexOf(toSnakeCase(category || undefined))

return index !== -1 ? categories[index] : null
}

export function toProjectStatus(status?: string | null): ProjectStatus | undefined {
const statuses = Object.values(ProjectStatus)
const index = statuses.map(toSnakeCase).indexOf(toSnakeCase(status || undefined))
Expand Down
35 changes: 20 additions & 15 deletions src/entities/Proposal/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@ import isUUID from 'validator/lib/isUUID'

import Time from '../../utils/date/Time'
import CoauthorModel from '../Coauthor/model'
import { CoauthorStatus } from '../Coauthor/types'
import { BUDGETING_START_DATE } from '../Grant/constants'
import { OldGrantCategory, SubtypeAlternativeOptions, isGrantSubtype } from '../Grant/types'
import SubscriptionModel from '../Subscription/model'

import { CoauthorStatus } from './../Coauthor/types'

import tsquery from './tsquery'
import { ProposalAttributes, ProposalStatus, ProposalType, isProposalType } from './types'
import { SITEMAP_ITEMS_PER_PAGE, isProposalStatus } from './utils'
Expand Down Expand Up @@ -82,7 +81,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
${objectValues(keys, [proposal])}
`

return this.query(sql) as any
return this.namedQuery('create_proposal', sql) as any
}

static update<U extends QueryPart = any, P extends QueryPart = any>(
Expand Down Expand Up @@ -111,7 +110,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
)}
`

return this.query(sql) as any
return this.namedQuery('update_proposal', sql) as any
}

static async countAll() {
Expand All @@ -127,7 +126,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
SQL`, `
)})`

const results = await this.query(query)
const results = await this.namedQuery('find_from_snapshot_ids', query)
return results.map((item) => ProposalModel.parse(item))
}

Expand All @@ -140,7 +139,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
OFFSET ${page * SITEMAP_ITEMS_PER_PAGE} LIMIT ${SITEMAP_ITEMS_PER_PAGE}
`

return this.query(query)
return this.namedQuery('get_sitemap_proposals', query)
}

static async activateProposals() {
Expand All @@ -153,7 +152,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
AND "start_at" <= now()
`

return this.rowCount(query)
return this.namedRowCount('activate_proposals_count', query)
}

static async getActiveGrantProposals(from?: Date, to?: Date) {
Expand All @@ -168,7 +167,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
ORDER BY created_at ASC
`

const result = await this.query(query)
const result = await this.namedQuery('active_grant_proposals', query)
return result.map(ProposalModel.parse)
}

Expand All @@ -183,7 +182,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
ORDER BY created_at ASC
`

const result = await this.query(query)
const result = await this.namedQuery('pending_new_grants', query)
return result.map(ProposalModel.parse)
}

Expand All @@ -197,7 +196,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
ORDER BY created_at ASC
`

const result = await this.query(query)
const result = await this.namedQuery('finishable_proposals', query)
return result.map(ProposalModel.parse)
}

Expand All @@ -218,7 +217,7 @@ export default class ProposalModel extends Model<ProposalAttributes> {
AND "id" IN (${join(ids)})
`

return this.rowCount(query)
return this.namedRowCount('finished_proposals_count', query)
}

private static getSubtypeQuery(subtype: string) {
Expand Down Expand Up @@ -275,7 +274,9 @@ export default class ProposalModel extends Model<ProposalAttributes> {
return 0
}

const result = await this.query(SQL`
const result = await this.namedQuery(
'proposals_total',
SQL`
SELECT COUNT(*) as "total"
FROM ${table(ProposalModel)} p
${conditional(!!subscribed, SQL`INNER JOIN ${table(SubscriptionModel)} s ON s."proposal_id" = p."id"`)}
Expand Down Expand Up @@ -307,7 +308,8 @@ export default class ProposalModel extends Model<ProposalAttributes> {
!!timeFrame && timeFrameKey === 'finish_at',
SQL`AND p."finish_at" > NOW() AND p."finish_at" < ${timeFrame}`
)}
${conditional(!!search, SQL`AND "rank" > 0`)}`)
${conditional(!!search, SQL`AND "rank" > 0`)}`
)

return (!!result && result[0] && Number(result[0].total)) || 0
}
Expand Down Expand Up @@ -367,7 +369,9 @@ export default class ProposalModel extends Model<ProposalAttributes> {
const sqlSnapshotIds = snapshotIds?.split(',').map((id) => SQL`${id}`)
const sqlSnapshotIdsJoin = sqlSnapshotIds ? join(sqlSnapshotIds) : null

const proposals = await this.query(SQL`
const proposals = await this.namedQuery(
'proposals_list',
SQL`
SELECT p.*${conditional(!!coauthor && !user, SQL`, c."coauthors"`)}
FROM ${table(ProposalModel)} p
${conditional(!!subscribed, SQL`INNER JOIN ${table(SubscriptionModel)} s ON s."proposal_id" = p."id"`)}
Expand Down Expand Up @@ -406,7 +410,8 @@ export default class ProposalModel extends Model<ProposalAttributes> {
min: 0,
max: 100,
defaultValue: 100,
})} ${offsetQuery(offset)}`)
})} ${offsetQuery(offset)}`
)

return proposals.map(this.parse)
}
Expand Down
2 changes: 1 addition & 1 deletion src/entities/Proposal/outcomeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export function getScoresResult(snapshotScores: number[], choices: string[]) {
return result
}

export async function getVotingResults(proposal: ProposalAttributes<any>, choices: string[]) {
export async function getVotingResults(proposal: ProposalAttributes, choices: string[]) {
const snapshotScores = await SnapshotGraphql.get().getProposalScores(proposal.snapshot_id)
return getScoresResult(snapshotScores, choices)
}
2 changes: 1 addition & 1 deletion src/entities/Proposal/testHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ export const JOB_CONTEXT_MOCK: CustomJobContext = {
return Promise.resolve(undefined)
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
updatePayload(payload: Record<string, unknown> | undefined): Promise<void> {
updatePayload(): Promise<void> {
return Promise.resolve(undefined)
},
log: jest.fn(),
Expand Down
6 changes: 1 addition & 5 deletions src/entities/Proposal/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function isAlreadyBannedName(name: string) {
}

export async function isAlreadyPointOfInterest(x: number, y: number) {
const pois = await Catalyst.get().getPOIs()
const pois = await Catalyst.getInstance().getPOIs()
return !!pois.find((position) => position[0] === x && position[1] === y)
}

Expand Down Expand Up @@ -86,10 +86,6 @@ export function isValidUpdateProposalStatus(current: ProposalStatus, next: Propo
}
}

export function isValidTransactionHash(transactionHash: string) {
return /^0x([A-Fa-f\d]{64})$/.test(transactionHash)
}

export function asNumber(value: string | number): number {
switch (typeof value) {
case 'number':
Expand Down
8 changes: 4 additions & 4 deletions src/entities/QuarterBudget/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export default class QuarterBudgetModel extends Model<QuarterBudgetAttributes> {
qb.finish_at > ${now}
`

const result = await this.query(query)
const result = await this.namedQuery('get_current_budget', query)
if (!result || result.length === 0) {
return null
}
Expand All @@ -126,7 +126,7 @@ export default class QuarterBudgetModel extends Model<QuarterBudgetAttributes> {
ON qcb.quarter_budget_id = qb.id;
`

const result = await this.query(query)
const result = await this.namedQuery('get_budget_for_date', query)
if (!result || result.length === 0) {
return null
}
Expand All @@ -148,7 +148,7 @@ export default class QuarterBudgetModel extends Model<QuarterBudgetAttributes> {
qb.finish_at > ${now}
`

const result = await this.query(query)
const result = await this.namedQuery('get_category_budget_for_current_quarter', query)
if (!result || result.length !== 1) {
return null
}
Expand All @@ -168,7 +168,7 @@ export default class QuarterBudgetModel extends Model<QuarterBudgetAttributes> {
WHERE "quarter_budget_id" = ${budgetUpdate.id}
AND "category" = ${newGrantCategory}
`
await this.query(query)
await this.namedQuery('update_budget', query)
}
}

Expand Down
7 changes: 5 additions & 2 deletions src/entities/SurveyTopic/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ export default class SurveyTopicModel extends Model<SurveyTopicAttributes> {
if (!isProposalType(proposalType)) return []
const proposalCategory = getProposalCategory(proposalType, proposalConfiguration)

return await this.query(SQL`
return await this.namedQuery(
'get_survey_topic',
SQL`
SELECT s.topic_id
FROM ${table(SurveyTopicModel)} s
INNER JOIN ${table(ProposalSurveyTopicModel)} ps ON ps."topic_id" = s."topic_id"
WHERE ps."proposal_type" = ${proposalType}
${conditional(!!proposalCategory, SQL`AND ps."proposal_sub_types" LIKE '%' || ${proposalCategory} || '%'`)}
;`)
;`
)
}
}
2 changes: 1 addition & 1 deletion src/entities/Votes/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export default class VotesModel extends Model<VoteAttributes> {
SQL`, `
)})`

const results = await this.query(query)
const results = await this.namedQuery('find_any_vote', query)
return results.map((score) => VotesModel.parse(score))
}
}
Loading

0 comments on commit 1ce25b8

Please sign in to comment.