Last active
April 29, 2022 02:43
-
-
Save joshtwist/65d6898c748798124ee3b0439ab86031 to your computer and use it in GitHub Desktop.
GraphQL Logging Policy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ZuploContext, ZuploRequest } from "@zuplo/runtime"; | |
import environment from "@app/environment"; | |
import { parse, visit } from "graphql"; | |
import { BQWriter } from "./bg-writer"; | |
interface LoggingEntry { | |
url: string; | |
method: string; | |
operation: string; | |
firstFieldName: string; | |
ip: string; | |
origin: string; | |
requestId: string; | |
userAgent: string; | |
timestamp: Date, | |
colo: string, | |
continent: string, | |
country: string, | |
region: string, | |
regionCode: string, | |
metroCode: string, | |
city: string, | |
postalCode: string, | |
latitude: string, | |
longitude: string, | |
timezone: string | |
}; | |
const bqWriter = new BQWriter<LoggingEntry>(environment.GCP_SERVICE_ACCOUNT_JSON, "fluent-stratum-330415", "graphql_logging", "requests"); | |
export default async function ( | |
request: ZuploRequest, | |
context: ZuploContext) { | |
if (request.method === "GET") { | |
return request; | |
} | |
const clone = request.clone(); | |
const body = await clone.json(); | |
const query = body.query; | |
const firstOperationDefinition = (ast) => ast.definitions[0]; | |
const firstFieldValueNameFromOperation = (operationDefinition) => operationDefinition.selectionSet.selections[0].name.value; | |
const parsedQuery = parse(query); | |
const fod = firstOperationDefinition(parsedQuery); | |
const operation = fod.operation; | |
const firstFieldName = firstFieldValueNameFromOperation(fod); | |
const xff = request.headers.get("x-forwarded-for"); | |
const ip = xff ? xff.split(",")[0] : "127.0.0.1"; | |
const cf = (request as any).cf; | |
const entry: LoggingEntry = { | |
url: request.url, | |
method: request.method, | |
operation, | |
firstFieldName, | |
ip, | |
origin: request.headers.get('origin'), | |
userAgent: request.headers.get('user-agent'), | |
requestId: context.requestId, | |
timestamp: new Date(), | |
colo: cf?.colo, | |
continent: cf?.continent, | |
country: cf?.country, | |
region: cf?.region, | |
regionCode: cf?.regionCode, | |
metroCode: cf?.metroCode, | |
city: cf?.city, | |
postalCode: cf?.postalCode, | |
latitude: cf?.latitude, | |
longitude: cf?.longitude, | |
timezone: cf?.timezone, | |
} | |
const p = bqWriter.insertRows([entry], context).catch(err => { | |
context.log.error(err.message); | |
}); | |
context.waitUntil(p); | |
return request; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment