(params: {
req: NextRequest
getUserInfoFromApiKey: GetUserInfoFromApiKeyFn
logger: Logger
loggerWithContext: LoggerWithContextFn
trackEvent: TrackEventFn
fetch: typeof globalThis.fetch
serverEnv: AdsEnv
})
| 145 | } |
| 146 | |
| 147 | export async function postAds(params: { |
| 148 | req: NextRequest |
| 149 | getUserInfoFromApiKey: GetUserInfoFromApiKeyFn |
| 150 | logger: Logger |
| 151 | loggerWithContext: LoggerWithContextFn |
| 152 | trackEvent: TrackEventFn |
| 153 | fetch: typeof globalThis.fetch |
| 154 | serverEnv: AdsEnv |
| 155 | }) { |
| 156 | const { |
| 157 | req, |
| 158 | getUserInfoFromApiKey, |
| 159 | loggerWithContext, |
| 160 | trackEvent, |
| 161 | fetch, |
| 162 | serverEnv, |
| 163 | } = params |
| 164 | |
| 165 | const authed = await requireUserFromApiKey({ |
| 166 | req, |
| 167 | getUserInfoFromApiKey, |
| 168 | logger: params.logger, |
| 169 | loggerWithContext, |
| 170 | trackEvent, |
| 171 | authErrorEvent: AnalyticsEvent.ADS_API_AUTH_ERROR, |
| 172 | }) |
| 173 | if (!authed.ok) return authed.response |
| 174 | |
| 175 | const { userId, userInfo, logger } = authed.data |
| 176 | |
| 177 | // Client IP comes in via the load balancer's X-Forwarded-For header. Every |
| 178 | // provider that targets or bills by IP (Gravity, Carbon, ...) needs this. |
| 179 | const forwardedFor = req.headers.get('x-forwarded-for') |
| 180 | const clientIp = forwardedFor |
| 181 | ? forwardedFor.split(',')[0].trim() |
| 182 | : (req.headers.get('x-real-ip') ?? undefined) |
| 183 | |
| 184 | let parsedBody: z.infer<typeof bodySchema> |
| 185 | try { |
| 186 | const json = await req.json() |
| 187 | const parsed = bodySchema.safeParse(json) |
| 188 | if (!parsed.success) { |
| 189 | logger.error({ parsed, json }, '[ads] Invalid request body') |
| 190 | return NextResponse.json( |
| 191 | { error: 'Invalid request body', details: parsed.error.format() }, |
| 192 | { status: 400 }, |
| 193 | ) |
| 194 | } |
| 195 | parsedBody = parsed.data |
| 196 | } catch { |
| 197 | return NextResponse.json( |
| 198 | { error: 'Invalid JSON in request body' }, |
| 199 | { status: 400 }, |
| 200 | ) |
| 201 | } |
| 202 | |
| 203 | const providerId: AdProviderId = parsedBody.provider ?? 'gravity' |
| 204 | const userAgent = |
no test coverage detected