Skip to content

Commit

Permalink
Revert "Remove supabase client from static props (#2951)"
Browse files Browse the repository at this point in the history
This reverts commit 76317e6.
  • Loading branch information
IanPhilips committed Oct 12, 2024
1 parent 1565357 commit f4df4f3
Show file tree
Hide file tree
Showing 12 changed files with 225 additions and 296 deletions.
2 changes: 0 additions & 2 deletions backend/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ import { getBets } from './get-bets'
import { getLiteUser, getUser } from './get-user'
import { getUsers } from './get-users'
import { getMarket } from './get-market'
import { getMarketProps } from './get-market-props'
import { getGroup } from './get-group'
import { getPositions } from './get-positions'
import { getLeagues } from './get-leagues'
Expand Down Expand Up @@ -326,7 +325,6 @@ const handlers: { [k in APIPath]: APIHandler<k> } = {
'group/:slug/unblock': unblockGroup,
groups: getGroups,
'market/:id': getMarket,
'get-market-props': getMarketProps,
'market/:id/lite': ({ id }) => getMarket({ id, lite: true }),
'slug/:slug': getMarket,
'market/:contractId/update': updateMarket,
Expand Down
175 changes: 0 additions & 175 deletions backend/api/src/get-market-props.ts
Original file line number Diff line number Diff line change
@@ -1,175 +0,0 @@
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { APIError } from 'common/api/utils'
import { convertContract } from 'common/supabase/contracts'
import { contractColumnsToSelect } from 'shared/utils'
import { first } from 'lodash'
import { convertGroup } from 'common/supabase/groups'
import { convertContractComment } from 'common/supabase/comments'
import { ContractMetric } from 'common/contract-metric'
import { ContractComment } from 'common/comment'

export const getMarketProps = async (
props: { id?: string; slug?: string } & { key: string }
) => {
const { key } = props
if (!process.env.API_SECRET) {
throw new APIError(500, 'API_SECRET is not set')
}
if (key !== process.env.API_SECRET) {
throw new APIError(401, 'Unauthorized')
}

const pg = createSupabaseDirectClient()
let contractId = 'id' in props ? props.id : undefined
const contractSlug = 'slug' in props ? props.slug : undefined
if (!contractId && !contractSlug) {
throw new APIError(400, 'id or slug is required')
}
if (!contractId) {
contractId = await pg.oneOrNone(
`select id from contracts where slug = $1`,
[contractSlug],
(r) => (r ? r.id : null)
)
if (!contractId) throw new APIError(404, 'Contract not found')
}
const results = await pg.multi(
`
select ${contractColumnsToSelect} from contracts
where id = $1;
select * from chart_annotations where contract_id = $1
order by event_time;
select g.id, g.name, g.slug, g.importance_score, g.privacy_status, g.total_members
from group_contracts gc
join groups g on gc.group_id = g.id
where gc.contract_id = $1
order by g.importance_score desc;
with parent_comments as (
select data, created_time, comment_id
from contract_comments
where contract_id = $1
and data->>'replyToCommentId' is null
order by created_time desc
limit 20
),
all_comments as (
select data, created_time, comment_id
from parent_comments
union all
select cc.data, cc.created_time, cc.comment_id
from contract_comments cc
join parent_comments pc on cc.data->>'replyToCommentId' = pc.comment_id
where cc.contract_id = $1
)
select data
from all_comments
order by created_time desc;
select data
from contract_comments
where contract_id = $1
and data->>'pinned' = 'true'
order by created_time desc;
select data
from user_contract_metrics
where contract_id = $1
and has_yes_shares
and exists (select 1 from contracts where id = $1 and mechanism = 'cpmm-1')
order by total_shares_yes desc
limit 50;
select data
from user_contract_metrics
where contract_id = $1
and has_no_shares
and exists (select 1 from contracts where id = $1 and mechanism = 'cpmm-1')
order by total_shares_no desc
limit 50;
select data
from user_contract_metrics
where contract_id = $1
and exists (select 1 from contracts where id = $1 and resolution_time is not null)
and answer_id is null
order by profit desc
limit 10;
select count(user_id) as count from user_contract_metrics
where contract_id = $1
and answer_id is null
and has_shares;
with contract as (
select creator_id, slug from contracts where id = $1
)
select title, slug
from dashboards
where visibility = 'public'
and (
importance_score > 0
or politics_importance_score > 0
or ai_importance_score > 0
or creator_id = (select creator_id from contract)
)
and items::jsonb @> concat('[{"type": "question", "slug": "', (select slug from contract), '"}]')::jsonb
order by importance_score desc,
politics_importance_score desc,
ai_importance_score desc,
created_time
limit 1;
`,
[contractId]
)
const contract = first(results[0]?.map(convertContract))
if (!contract) throw new APIError(404, 'Contract not found')
const chartAnnotations = results[1]
const topics = results[2].map(convertGroup)
const allComments = results[3].map(convertContractComment)
const comments = filterComments(allComments)
const pinnedComments = results[4].map(convertContractComment)
const yesMetrics = results[5].map((r) => r.data as ContractMetric)
const noMetrics = results[6].map((r) => r.data as ContractMetric)
const topContractMetrics = results[7].map((r) => r.data as ContractMetric)
const totalPositions = results[8]?.[0]?.count ?? 0
const dashboards = results[9]
return {
contract,
chartAnnotations,
topics,
comments,
pinnedComments,
userPositionsByOutcome: {
YES: yesMetrics,
NO: noMetrics,
},
topContractMetrics,
totalPositions,
dashboards,
}
}

const filterComments = (comments: ContractComment[]) => {
const parents = comments.filter((c) => !c.replyToCommentId)
const approximateTotalComments = 25
const targetComments = [] as ContractComment[]
for (const parent of parents) {
const parentComment = parent as ContractComment
targetComments.push(parentComment)
if (targetComments.length >= approximateTotalComments) break

const childrenComments = comments.filter(
(c) => (c as ContractComment).replyToCommentId === parentComment.id
)

const remainingSpace = approximateTotalComments - targetComments.length
const childrenToAdd = childrenComments.slice(0, remainingSpace)
targetComments.push(...childrenToAdd)

if (targetComments.length >= approximateTotalComments) break
}
return targetComments
}
8 changes: 0 additions & 8 deletions common/src/api/market-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,6 @@ export type LiteMarket = {
lastUpdatedTime?: number
lastBetTime?: number
marketTier?: MarketTierType
deleted?: boolean
visibility?: string
token?: string
siblingContractId?: string
}
export type ApiAnswer = Omit<
Answer & {
Expand Down Expand Up @@ -125,8 +121,6 @@ export function toLiteMarket(contract: Contract): LiteMarket {
marketTier,
token,
siblingContractId,
visibility,
deleted,
} = contract

const { p, totalLiquidity } = contract as any
Expand Down Expand Up @@ -178,8 +172,6 @@ export function toLiteMarket(contract: Contract): LiteMarket {
marketTier,
token,
siblingContractId,
visibility,
deleted,

// Manifold love props.
loverUserId1,
Expand Down
25 changes: 0 additions & 25 deletions common/src/api/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ import { PrivateMessageChannel } from 'common/supabase/private-messages'
import { Notification } from 'common/notification'
import { NON_POINTS_BETS_LIMIT } from 'common/supabase/bets'
import { ContractMetric } from 'common/contract-metric'
import { ChartAnnotation } from 'common/supabase/chart-annotations'

// mqp: very unscientific, just balancing our willingness to accept load
// with user willingness to put up with stale data
Expand Down Expand Up @@ -472,30 +471,6 @@ export const API = (_apiTypeCheck = {
cache: DEFAULT_CACHE_STRATEGY,
props: z.object({ id: z.string(), lite: coerceBoolean.optional() }),
},
'get-market-props': {
method: 'GET',
visibility: 'public',
authed: false,
returns: {} as {
contract: Contract
chartAnnotations: ChartAnnotation[]
topics: Topic[]
comments: ContractComment[]
pinnedComments: ContractComment[]
userPositionsByOutcome: {
YES: ContractMetric[]
NO: ContractMetric[]
}
topContractMetrics: ContractMetric[]
totalPositions: number
dashboards: Dashboard[]
},
props: z.object({
slug: z.string().optional(),
id: z.string().optional(),
key: z.string(),
}),
},
// deprecated. use /market/:id?lite=true instead
'market/:id/lite': {
method: 'GET',
Expand Down
Loading

0 comments on commit f4df4f3

Please sign in to comment.