// packages/graphql/examples/demo.vk // Self-contained runnable verification suite for `graphql` (`1.0.0`): // Complex document parser (aliases, variables + defaults, `@skip` / `@include`, named & inline // fragments), homoiconic `from-quote` schema execution (queries + mutations + `__typename`), // `__schema` / `__type` introspection, `Dataloader` N+1 batching + caching, and `web/App` // `POST /graphql` + `GET /graphql` Light-First GraphiQL Explorer dispatch! use [ web gql = graphql parser = graphql/parser ] assert-eq = fn [label str, got any, want any] any [ if got != want [ println `[FAIL] {label}: got {mold got}, expected {mold want}` return (err `assert-eq failed: {label}`) ] println `[PASS] {label}` .ok ] assert-true = fn [label str, cond bool] any [ if not cond [ println `[FAIL] {label}` return (err `assert-true failed: {label}`) ] println `[PASS] {label}` .ok ] main = fn [] any [ println '=== graphql 1.0.0 Verification Suite ===' // 1. Parser verification: operation, variables with defaults, aliases, nested input objects, // `@include` / `@skip`, named fragments (`...UserFields`), and inline fragments (`... on User`) complex_doc_str = ' # GraphQL query exercising full June 2018 / Oct 2021 grammar query FetchDashboard($primaryId: ID! = "u-1", $secondaryId: ID!, $hideRole: Boolean = false, $withPosts: Boolean = true) { primary: user(id: $primaryId) { __typename ...UserFields ... on User @include(if: $withPosts) { posts(filter: { published: true, tags: ["veko", "graphql"] }) { id title } } } secondary: user(id: $secondaryId) { id name } } fragment UserFields on User { id name role @skip(if: $hideRole) } ' parsed_doc = parser/parse-document/or complex_doc_str [e -> return e] _ = assert-eq/or 'Parser extracts 1 named query operation' (len parsed_doc.operations) 1 [e -> return e] _ = assert-eq/or 'Operation name == FetchDashboard' parsed_doc.operations[0].name 'FetchDashboard' [e -> return e] _ = assert-eq/or 'Operation defines 4 typed variables' (len parsed_doc.operations[0].variables) 4 [e -> return e] _ = assert-eq/or 'Default value on $primaryId == u-1' parsed_doc.operations[0].variables[0].default_val 'u-1' [e -> return e] _ = assert-true/or 'Named fragment UserFields registered in document' (map/has? parsed_doc.fragments 'UserFields') [e -> return e] // 2. Prove `Dataloader` batches multiple duplicate & distinct keys into 1 batch call + caches repeats users_db = { 'u-1' = { id = 'u-1', name = 'Ada Lovelace', role = .ADMIN } 'u-2' = { id = 'u-2', name = 'Grace Hopper', role = .MEMBER } 'u-3' = { id = 'u-3', name = 'Ken Thompson', role = .MEMBER } } posts_db = [ { id = 'p-10', author_id = 'u-1', title = 'Zero-Codegen GraphQL in Veko', published = true } { id = 'p-11', author_id = 'u-1', title = 'Draft Internal Notes', published = false } { id = 'p-12', author_id = 'u-2', title = 'Deterministic Wasm 3.0', published = true } { id = 'p-13', author_id = 'u-3', title = 'SQLite Slotted B-Trees', published = true } ] mut user_loader = gql/new-dataloader fn [batch_ids block] block [ mut out = block/with-cap (len batch_ids) mut i = 0 while i < (len batch_ids) [ uid = str/append '' batch_ids[i] push mut out (map/get/or users_db uid [ .null ]) i = i + 1 ] out ] // Simulate 5 child resolver lookups across 3 unique authors (`u-1` x2, `u-2` x2, `u-3` x1) loaded_authors = gql/load-many/or mut user_loader ['u-1' 'u-2' 'u-1' 'u-3' 'u-2'] [e -> return e] _ = assert-eq/or 'Dataloader returns all 5 requested authors in order' (len loaded_authors) 5 [e -> return e] _ = assert-eq/or 'Dataloader deduplicated 5 lookups into 1 single batch call' user_loader.batch_calls 1 [e -> return e] _ = assert-eq/or 'Subsequent load-one hits per-request cache without extra batch call' (map/get (gql/load-one mut user_loader 'u-2') 'name') 'Grace Hopper' [e -> return e] _ = assert-eq/or 'Dataloader batch_calls remains 1 after cached load-one' user_loader.batch_calls 1 [e -> return e] _ = assert-true/or 'Dataloader recorded cache hits' (user_loader.cache_hits >= 1) [e -> return e] // 3. Homoiconic `from-quote` Schema Builder + Query & Mutation Execution schema = gql/from-quote (quote [ enum Role [ADMIN MEMBER GUEST] object Post [ id ID! title String! published Boolean! author User! ] object User [ id ID! name String! role Role posts [Post!]! ] query [ user [id ID!] User posts [publishedOnly Boolean] [Post!]! ] mutation [ createPost [authorId ID!, title String!] Post! ] ]) { 'Query.user' = fn [_parent any, args map, ctx any] any [ uid = str/append '' (map/get args 'id') map/get/or ctx.users uid [ .null ] ] 'Query.posts' = fn [_parent any, args map, ctx any] any [ pub_only = (map/get/or args 'publishedOnly' [ false ]) == true mut res = [] mut i = 0 while i < (len ctx.posts) [ p = ctx.posts[i] if (not pub_only) or p.published == true [ push mut res p ] i = i + 1 ] res ] 'User.posts' = fn [user any, args map, ctx any] any [ uid = str/append '' (map/get user 'id') flt = map/get/or args 'filter' [ {} ] want_pub = map/get/or flt 'published' [ .null ] mut res = [] mut i = 0 while i < (len ctx.posts) [ p = ctx.posts[i] pub_ok = if want_pub == .null [ true ] else [ p.published == want_pub ] if p.author_id == uid and pub_ok [ push mut res p ] i = i + 1 ] res ] 'Post.author' = fn [post any, _args map, ctx any] any [ aid = str/append '' (map/get post 'author_id') // Resolved from pre-batched Dataloader cache in `ctx`! mut ld = ctx.user_loader gql/load-one mut ld aid ] 'Mutation.createPost' = fn [_parent any, args map, _ctx any] any [ { id = 'p-99' author_id = (str/append '' (map/get args 'authorId')) title = (str/append '' (map/get args 'title')) published = true } ] } exec_ctx = { users = users_db posts = posts_db user_loader = user_loader } // Execute `complex_doc_str`: `$primaryId` uses default `"u-1"`, `$hideRole = true` skips `role`! q_res = gql/execute schema complex_doc_str { secondaryId = 'u-2', hideRole = true, withPosts = true } exec_ctx _ = assert-eq/or 'Complex GraphQL query executes with 0 errors' (len q_res.errors) 0 [e -> return e] primary_u = map/get q_res.data 'primary' secondary_u = map/get q_res.data 'secondary' _ = assert-eq/or 'Alias primary.__typename == User' (map/get primary_u '__typename') 'User' [e -> return e] _ = assert-eq/or 'Fragment spread resolved primary.name == Ada Lovelace' (map/get primary_u 'name') 'Ada Lovelace' [e -> return e] _ = assert-eq/or '@skip(if: $hideRole) omitted role field when true' (map/has? primary_u 'role') false [e -> return e] u1_posts = map/get primary_u 'posts' _ = assert-eq/or 'Nested input-object filter { published: true } returned 1 published post for u-1' (len u1_posts) 1 [e -> return e] _ = assert-eq/or 'Alias secondary.name == Grace Hopper' (map/get secondary_u 'name') 'Grace Hopper' [e -> return e] // Execute Mutation (`createPost` + nested `author` resolved via primed Dataloader) mut_doc = 'mutation NewArticle($aid: ID!, $title: String!) { createPost(authorId: $aid, title: $title) { id title author { id name role } } }' m_res = gql/execute schema mut_doc { aid = 'u-3', title = 'Homoiconic Schemas' } exec_ctx _ = assert-eq/or 'GraphQL mutation executes with 0 errors' (len m_res.errors) 0 [e -> return e] created_p = map/get m_res.data 'createPost' _ = assert-eq/or 'Mutation returned created post id == p-99' (map/get created_p 'id') 'p-99' [e -> return e] _ = assert-eq/or 'Mutation nested Post.author resolved Ken Thompson' (map/get (map/get created_p 'author') 'name') 'Ken Thompson' [e -> return e] _ = assert-eq/or 'Enum value serialized as ADMIN/MEMBER string' (map/get (map/get created_p 'author') 'role') 'MEMBER' [e -> return e] // 4. Built-in `__schema` and `__type` Introspection intro_res = gql/execute schema '{ __schema { queryType { name } mutationType { name } types { kind name } } roleType: __type(name: "Role") { kind name enumValues { name } } }' {} exec_ctx _ = assert-eq/or 'Introspection query executes with 0 errors' (len intro_res.errors) 0 [e -> return e] isch = map/get intro_res.data '__schema' _ = assert-eq/or '__schema.queryType.name == Query' (map/get (map/get isch 'queryType') 'name') 'Query' [e -> return e] _ = assert-eq/or '__schema.mutationType.name == Mutation' (map/get (map/get isch 'mutationType') 'name') 'Mutation' [e -> return e] rtype = map/get intro_res.data 'roleType' _ = assert-eq/or '__type(name: "Role") kind == ENUM with 3 enumValues' (len (map/get rtype 'enumValues')) 3 [e -> return e] // 5. Mount onto `web/App` and dispatch `GET /graphql` Explorer + `POST /graphql` JSON execution mut app = web/new-app _ = gql/mount-graphql/ctx_fn/title mut app '/graphql' schema (fn [_req web/Request] any [ exec_ctx ]) 'Veko GraphQL Studio' get_explorer_req = web/Request { method = 'GET' path = '/graphql' target = '/graphql' query = {} params = {} headers = { 'Accept' = 'text/html' } body = (bytes/with-cap 0) } get_resp = web/handle-request app get_explorer_req html_body = bytes/to-str get_resp.body _ = assert-eq/or 'GET /graphql returns 200 OK HTML5 GraphiQL Explorer' get_resp.status 200 [e -> return e] _ = assert-true/or 'GraphiQL Explorer is Light-First (data-theme="light") & zero-CDN' ((str/contains? html_body 'data-theme="light"') and (str/contains? html_body 'Veko GraphQL Studio')) [e -> return e] post_payload = json/encode { query = 'query($onlyPub: Boolean) { posts(publishedOnly: $onlyPub) { id title author { name } } }' variables = { onlyPub = true } } post_req = web/Request { method = 'POST' path = '/graphql' target = '/graphql' query = {} params = {} headers = { 'Content-Type' = 'application/json' } body = (bytes/from-str post_payload) } post_resp = web/handle-request app post_req _ = assert-eq/or 'POST /graphql returns 200 OK JSON response' post_resp.status 200 [e -> return e] post_json = json/decode (bytes/to-str post_resp.body) http_posts = map/get (map/get post_json 'data') 'posts' _ = assert-eq/or 'POST /graphql returns 3 published posts with nested authors' (len http_posts) 3 [e -> return e] _ = assert-eq/or 'POST /graphql omits errors key when 0 errors occurred' (map/has? post_json 'errors') false [e -> return e] println 'ALL graphql 1.0.0 TESTS PASSED' .ok ] res = main if err? res [ println (mold res) os/exit 1 ]