Skip to content

Instantly share code, notes, and snippets.

@zhyd1997
Last active April 16, 2024 10:24
Show Gist options
  • Save zhyd1997/0e2f4ac8f91d8f29f4101a6369549ffc to your computer and use it in GitHub Desktop.
Save zhyd1997/0e2f4ac8f91d8f29f4101a6369549ffc to your computer and use it in GitHub Desktop.
custom transform function for json schema from supabase.
# Step 1: Download schema types from supabase via download button in supabase dashboard `API Docs` or the script below
# https://supabase.com/docs/guides/api/rest/generating-types
npx supabase gen types typescript --project-id "$PROJECT_REF" --schema public > types/supabase.ts
# Step 2: Transform TS schema types to json
npx ts-json-schema-generator --path './supabase.ts' --type 'Database' -o "./supabase.js"
# Step 3: Copy `schema.definitions.Database.properties['public'].properties.Tables` value into https://jsoneditoronline.org/
# Step 4: Applied custom transform function below:
# path: util.js
https://gist.github.com/Yadong-OneXTech/67e6de42778c0fd3b28256260f0128d6
# Step 5: `Copy compacted` string.
// apply to https://jsoneditoronline.org/
function query (data) {
const raw = _.chain(data)
.value()
return Object.entries(raw).map(([key, value]) => {
if (key === '_prisma_migrations') return
const row = value['properties']['Row']['properties']
const generatedRowValue = {}
Object.entries(row).map(([s, t]) => {
const { type } = t || {}
const v = Array.isArray(type) ? type[0] : type
generatedRowValue[s] = v
return { [s]: v }
})
const relation = value['properties']['Relationships']['items']
const relationShips = Array.isArray(relation) ? relation.map((r) => {
const obj = Object.entries(r['properties']).map(([key, value]) => {
return { [key]: value?.const ?? value?.items?.const }
})
return obj
}) : relation?.properties ? Object.entries(relation['properties']).map(([key, value]) => {
return { [key]: value?.const ?? value?.items?.const }
}) : null
generatedRowValue['relationShips'] = relationShips
return { [key]: generatedRowValue }
}).filter(Boolean)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment