-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.wp
More file actions
823 lines (692 loc) · 19.6 KB
/
example.wp
File metadata and controls
823 lines (692 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
## Web Pipe Complete Tutorial
# This is a comprehensive tutorial covering all Web Pipe features with modern syntax.
#
# Run the server:
# cargo run -- example.wp
# Run tests:
# cargo run -- example.wp --test
#
# Expected database schema:
# CREATE TABLE teams (id serial primary key, name text, created_at timestamp default now());
# CREATE TABLE users (id serial primary key, login text unique, email text, password_hash text,
# type text default 'user', status text default 'active', created_at timestamp default now());
## ========================================
## 1) Configuration
## ========================================
config pg {
host: $WP_PG_HOST || "localhost"
port: $WP_PG_PORT || "5432"
database: $WP_PG_DATABASE || "express-test"
user: $WP_PG_USER || "postgres"
password: $WP_PG_PASSWORD || "postgres"
ssl: false
initialPoolSize: 5
maxPoolSize: 20
}
config auth {
sessionTtl: 604800
cookieName: "wp_session"
cookieSecure: false
cookieHttpOnly: true
cookieSameSite: "Lax"
cookiePath: "/"
}
config cache {
enabled: true
defaultTtl: 60
maxCacheSize: 10485760
}
config log {
enabled: true
format: "json"
level: "debug"
includeBody: false
includeHeaders: true
maxBodySize: 1024
timestamp: true
}
config graphql {
endpoint: "/graphql"
}
## ========================================
## 2) Variables: Reusable Snippets
## ========================================
# SQL variables
pg findTeamById = `SELECT * FROM teams WHERE id = $1`
pg listTeams = `SELECT * FROM teams ORDER BY id`
pg insertTeam = `INSERT INTO teams (name) VALUES ($1) RETURNING *`
# Handlebars partials - define defaults first for inline block usage
handlebars title = `Default Title`
handlebars body = `Default body content`
handlebars layout = `
<!DOCTYPE html>
<html>
<head>
<title>{{>title}}</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-8">
{{>body}}
</body>
</html>
`
handlebars helloPartial = `<p class="greeting">Hello, {{name}}!</p>`
handlebars teamCard = `
<div class="team-card bg-white p-4 rounded shadow">
<h3 class="team-name font-bold">{{name}}</h3>
<p class="team-id text-gray-600">ID: {{id}}</p>
</div>
`
## ========================================
## 3) Pipelines: Reusable Middleware Chains
## ========================================
pipeline loadTeam =
|> pg([(.params.id // .query.id // .body.id | tonumber)]): findTeamById
|> jq: `{ team: .data.findTeamById.rows[0] }`
## ========================================
## 4) Basic Routes: GET, POST, PUT, DELETE
## ========================================
# Simple GET with path parameter
GET /hello/:name
|> jq: `{ name: .params.name }`
|> handlebars: `{{>helloPartial}}`
# POST with body
POST /echo
|> jq: `{
method: .method,
body: .body,
headers: .headers
}`
# PUT with path parameter and body
PUT /teams/:id
|> jq: `{
id: .params.id,
name: .body.name,
action: "update"
}`
# DELETE with path parameter
DELETE /teams/:id
|> jq: `{
id: .params.id,
deleted: true
}`
## ========================================
## 5) JQ Transformations
## ========================================
GET /jq-demo/:id
|> jq: `{
id: (.params.id | tonumber),
query: .query,
timestamp: now,
computed: (.params.id | tonumber) * 2
}`
## ========================================
## 6) Handlebars Templating
## ========================================
GET /hello-page/:name
|> jq: `{
pageTitle: "Hello Page",
name: .params.name
}`
|> handlebars: `
{{#*inline "title"}}{{pageTitle}}{{/inline}}
{{#*inline "body"}}
<h1 class="text-3xl font-bold">Hello, {{name}}!</h1>
<p class="welcome-text mt-4">Welcome to Web Pipe</p>
{{/inline}}
{{>layout}}
`
GET /teams-page
|> pg: listTeams @result(teams)
|> jq: `{
pageTitle: "Teams",
teams: .data.teams.rows
}`
|> handlebars: `
{{#*inline "title"}}{{pageTitle}}{{/inline}}
{{#*inline "body"}}
<h1 class="text-3xl font-bold mb-6">Teams</h1>
<div class="grid grid-cols-3 gap-4">
{{#each teams}}
{{>teamCard}}
{{/each}}
</div>
{{/inline}}
{{>layout}}
`
## ========================================
## 7) Postgres/SQL Queries (Modern Syntax)
## ========================================
# Simple query with inline parameters
GET /teams
|> pg: listTeams @result(teams)
|> jq: `{
teams: .data.teams.rows,
count: (.data.teams.rows | length)
}`
GET /teams/:id
|> pipeline: loadTeam
# INSERT with inline parameters
POST /teams
|> validate: `{ name: string(3..50) }`
|> pg([.body.name]): insertTeam
|> jq: `{
team: .data.insertTeam.rows[0],
created: true
}`
# Multiple queries with @result tags
GET /multi-query/:id
|> pg: listTeams @result(allTeams)
|> pg([(.params.id | tonumber)]): findTeamById @result(specificTeam)
|> jq: `{
allTeams: .data.allTeams.rows,
specificTeam: .data.specificTeam.rows[0]
}`
## ========================================
## 8) Lua Scripting
## ========================================
GET /lua/echo/:id
|> lua: `
return {
from = "lua",
id = request.params.id,
method = request.method,
luaVersion = _VERSION
}
`
GET /lua/teams/:id
|> lua: `
local id = tonumber(request.params.id)
local result, err = executeSql("SELECT * FROM teams WHERE id = $1", {id})
if err then
return {
errors = {{ type = "sqlError", message = err }}
}
end
return {
team = result.rows[1],
found = #result.rows > 0
}
`
GET /lua/env
|> lua: `
local dbHost = getEnv("WP_PG_HOST") or "not set"
return {
dbHost = dbHost,
env = "retrieved from environment"
}
`
## ========================================
## 9) Result Routing
## ========================================
GET /result-demo
|> jq: `{
errors: [{
type: "validationError",
field: "email",
message: "Email is required"
}]
}`
|> result
ok(200):
|> jq: `{ success: true, data: .data }`
validationError(400):
|> jq: `{
error: "Validation failed",
field: .errors[0].field,
message: .errors[0].message
}`
authError(401):
|> jq: `{ error: "Unauthorized", message: .errors[0].message }`
sqlError(500):
|> jq: `{
error: "Database error",
sqlstate: .errors[0].sqlstate,
message: .errors[0].message
}`
default(500):
|> jq: `{ error: "Internal server error" }`
## ========================================
## 10) Validation
## ========================================
POST /validate-demo
|> validate: `{
name: string(3..50),
email: email,
age: number,
website: string(5..100)
}`
|> result
ok(200):
|> jq: `{ success: true, data: .body }`
validationError(400):
|> jq: `{
error: "Validation failed",
field: .errors[0].field,
rule: .errors[0].rule,
message: .errors[0].message
}`
## ========================================
## 11) Authentication
## ========================================
POST /login
|> validate: `{
login: string(3..50),
password: string(6..100)
}`
|> auth: "login"
|> result
ok(200):
|> jq: `{
success: true,
user: {
id: .user.id,
login: .user.login,
email: .user.email
}
}`
validationError(400):
|> jq: `{ success: false, error: .errors[0].message }`
authError(401):
|> jq: `{ success: false, error: .errors[0].message }`
POST /register
|> validate: `{
login: string(3..50),
email: email,
password: string(8..100)
}`
|> auth: "register"
|> result
ok(201):
|> jq: `{ success: true, message: "Registration successful" }`
validationError(400):
|> jq: `{ success: false, error: .errors[0].message }`
authError(409):
|> jq: `{ success: false, error: .errors[0].message }`
POST /logout
|> auth: "logout"
|> jq: `{ success: true, message: "Logged out" }`
GET /me
|> auth: "optional"
|> jq: `{
authenticated: (.user != null),
user: .user
}`
GET /protected
|> auth: "required"
|> result
ok(200):
|> jq: `{
message: "Access granted",
user: .user.login
}`
authError(401):
|> jq: `{ error: "Authentication required" }`
## ========================================
## 12) Caching
## ========================================
# Basic caching
GET /cache-basic
|> cache: `ttl: 60, enabled: true`
|> jq: `{
message: "This response is cached for 60 seconds",
timestamp: now
}`
# Cache with custom key template
GET /user/:id/profile
|> cache: `keyTemplate: user-profile-{params.id}, ttl: 120, enabled: true`
|> jq: `{
userId: .params.id,
profile: "User profile data",
fetchedAt: now
}`
# Cache with query parameters in key
GET /search
|> cache: `keyTemplate: search-{query.q}-{query.category}, ttl: 300, enabled: true`
|> jq: `{
query: .query.q,
category: .query.category,
results: ["result1", "result2"],
cached: true
}`
## ========================================
## 13) Logging and Debugging
## ========================================
GET /log-demo
|> log: `level: info, includeHeaders: true, includeBody: true`
|> jq: `{ message: "This request will be logged" }`
GET /debug-demo
|> jq: `{ step: "first", data: [1, 2, 3] }`
|> debug: `After first transformation`
|> jq: `{ step: "second", sum: (.data | add) }`
|> debug: `After computing sum`
## ========================================
## 14) Cookies
## ========================================
GET /cookies
|> jq: `{
message: "Cookie demo",
receivedCookies: .cookies,
setCookies: [
"sessionId=abc123; HttpOnly; Secure; Max-Age=3600",
"theme=dark; Path=/; Max-Age=86400"
]
}`
## ========================================
## 15) HTTP Fetch (Modern Inline Syntax)
## ========================================
# Simple GET request with inline string
GET /fetch-demo
|> fetch("https://api.github.com/zen")
|> jq: `{
zen: .data.response,
status: .data.status
}`
# Dynamic URL with inline expression
GET /fetch-user/:id
|> fetch("https://api.github.com/users/" + (.params.id))
|> jq: `{
user: .data.response,
success: (.data.status == 200)
}`
# Named fetch result with @result tag
GET /fetch-named
|> fetch("https://api.github.com/zen") @result(githubZen)
|> jq: `{
zen: .data.githubZen.response,
fetchedAt: now
}`
# Complex fetch with traditional approach (for custom headers/body)
GET /fetch-post
|> jq: `{
fetchUrl: "https://httpbin.org/post",
fetchMethod: "POST",
fetchBody: { name: "test", value: 123 },
fetchHeaders: { "Content-Type": "application/json" }
}`
|> fetch: `_`
|> jq: `{
response: .data.response,
success: (.data.status == 200)
}`
## ========================================
## 16) GraphQL (Modern Inline Syntax)
## ========================================
graphqlSchema = `
type Team {
id: ID!
name: String!
createdAt: String
}
type Query {
teams: [Team!]!
team(id: Int!): Team
currentTime: String!
}
type Mutation {
createTeam(name: String!): Team!
}
`
# Query resolvers
query teams =
|> pg: listTeams
|> jq: `.data.listTeams.rows`
query team =
|> pg([.id]): findTeamById
|> jq: `.data.findTeamById.rows[0]`
query currentTime =
|> pg: `SELECT NOW()::text as time`
|> jq: `.data.rows[0].time`
# Mutation resolvers
mutation createTeam =
|> validate: `{ name: string(3..50) }`
|> pg([.name]): insertTeam
|> jq: `.data.insertTeam.rows[0]`
# GraphQL endpoint with inline object parameters
GET /graphql-demo
|> graphql: `
query {
teams {
id
name
}
currentTime
}
`
GET /graphql-with-args/:id
|> graphql({ id: (.params.id | tonumber) }): `
query($id: Int!) {
team(id: $id) {
id
name
}
}
`
POST /graphql-mutation
|> graphql({ name: .body.name }): `
mutation($name: String!) {
createTeam(name: $name) {
id
name
}
}
`
## ========================================
## 17) Tags & Feature Flags
## ========================================
pipeline featureFlags =
|> lua: `
-- Enable feature for 50% of requests
local rand = math.random()
setFlag("new-ui", rand < 0.5)
-- Always enable beta for staff
if request.user and request.user.type == "staff" then
setFlag("beta-features", true)
end
return {}
`
GET /feature-demo
|> jq: `{ version: "1.0", ui: "classic" }` @!flag(new-ui)
|> jq: `{ version: "2.0", ui: "modern" }` @flag(new-ui)
# Environment-specific middleware
GET /env-demo
|> jq: `{ env: "production", debug: false }` @env(production)
|> jq: `{ env: "development", debug: true }` @env(development)
|> log: `level: debug` @!env(production)
## ========================================
## 18) Async & Join (Parallel Execution)
## ========================================
# Sequential (slow) - takes ~6 seconds
GET /sequential-slow
|> fetch("https://httpbin.org/delay/2")
|> jq: `{ first: .data.response }`
|> fetch("https://httpbin.org/delay/2")
|> jq: `. + { second: .data.response }`
|> fetch("https://httpbin.org/delay/2")
|> jq: `. + { third: .data.response }`
# Parallel (fast) - takes ~2 seconds total
GET /parallel-fast
|> fetch("https://httpbin.org/delay/2") @async(req1)
|> fetch("https://httpbin.org/delay/2") @async(req2)
|> fetch("https://httpbin.org/delay/2") @async(req3)
|> join: `req1, req2, req3`
|> jq: `{
message: "All 3 requests completed in parallel!",
results: [
.async.req1.data.response,
.async.req2.data.response,
.async.req3.data.response
]
}`
# Parallel GraphQL queries
GET /graphql-parallel
|> graphql: `query { teams { id name } }` @async(teamsQuery)
|> graphql: `query { currentTime }` @async(timeQuery)
|> join: `teamsQuery, timeQuery`
|> jq: `{
teams: .async.teamsQuery.data.teams,
loadedAt: .async.timeQuery.data.currentTime,
executionMode: "parallel"
}`
## ========================================
## 19) Tests: Comprehensive BDD Framework
## ========================================
# Basic route testing with let variables
describe "hello route with variables"
let name = "World"
it "greets by name using let variable"
when calling GET /hello/{{name}}
then status is 200
and selector `p.greeting` text equals "Hello, {{name}}!"
# Testing with CSS selectors
describe "teams page with selectors"
with mock pg.listTeams returning `{
"rows": [
{ "id": 1, "name": "Platform" },
{ "id": 2, "name": "Growth" }
]
}`
it "renders team cards with correct structure"
when calling GET /teams-page
then status is 200
and contentType is "text/html"
and selector `.team-card` exists
and selector `.team-name` text contains "Platform"
and selector `.team-id` text equals "ID: 1"
# Testing JSON responses
describe "teams API"
with mock pg.listTeams returning `{
"rows": [
{ "id": 1, "name": "Platform" },
{ "id": 2, "name": "Growth" }
]
}`
it "lists all teams"
when calling GET /teams
then status is 200
and output contains `{ "teams": [{ "id": 1 }] }`
and output `.count` equals 2
it "gets team by id with let variable"
let teamId = "1"
when calling GET /teams/{{teamId}}
then status is 200
and output contains `{ "team": { "id": 1, "name": "Platform" } }`
# Testing pipelines directly
describe "pipeline testing"
with mock pg.findTeamById returning `{
"rows": [{ "id": 42, "name": "Test Team" }]
}`
it "executes loadTeam pipeline"
let id = "42"
when executing pipeline loadTeam
with input `{ "params": { "id": "{{id}}" } }`
then output equals `{
"team": { "id": 42, "name": "Test Team" }
}`
it "supports jq path assertions"
when executing pipeline loadTeam
with input `{ "params": { "id": "42" } }`
then output `.team.id` equals 42
and output `.team.name` equals "Test Team"
# Testing validation
describe "validation"
it "catches validation errors"
when calling POST /validate-demo
with body `{ "name": "ab", "email": "invalid" }`
then status is 400
and output contains `{ "error": "Validation failed" }`
it "passes valid input"
when calling POST /validate-demo
with body `{ "name": "John Doe", "email": "john@example.com", "age": 30, "website": "https://example.com" }`
then status is 200
and output `.success` equals true
# Testing result routing
describe "result routing"
it "maps validation errors to 400"
when calling GET /result-demo
then status is 400
and output contains `{ "error": "Validation failed" }`
and output `.field` equals "email"
# Testing with regex
describe "regex matching"
it "supports output matches regex"
let name = "Test"
when calling GET /hello/{{name}}
then output matches `Hello,\s*{{name}}!`
# Testing status ranges
describe "status codes"
it "supports status ranges"
when calling GET /hello/World
then status in 200..299
it "checks exact status"
when calling GET /result-demo
then status is 400
# Testing JQ transformations
describe "jq demo"
it "transforms params correctly"
let id = "42"
when calling GET /jq-demo/{{id}}
then status is 200
and output `.id` equals 42
and output `.computed` equals 84
# Testing multiple let variables
describe "multiple let variables"
let firstName = "John"
let lastName = "Doe"
it "uses multiple variables in test"
when calling GET /hello/{{firstName}} {{lastName}}
then status is 200
and selector `p.greeting` text contains "{{firstName}}"
# Testing with mock variations
describe "mock variations"
it "test with empty results"
with mock pg.listTeams returning `{ "rows": [] }`
when calling GET /teams
then status is 200
and output `.count` equals 0
it "test with multiple results"
with mock pg.listTeams returning `{
"rows": [
{ "id": 1, "name": "Team 1" },
{ "id": 2, "name": "Team 2" },
{ "id": 3, "name": "Team 3" }
]
}`
when calling GET /teams
then status is 200
and output `.count` equals 3
and output `.teams | map(.id)` equals `[1, 2, 3]`
# Testing HTML page structure
describe "hello page rendering"
let userName = "Alice"
it "renders complete HTML page"
when calling GET /hello-page/{{userName}}
then status is 200
and contentType is "text/html"
and selector `h1` text equals "Hello, {{userName}}!"
and selector `.welcome-text` text contains "Welcome to Web Pipe"
## ========================================
## Summary
## ========================================
# This tutorial covers:
# ✓ Configuration (pg, auth, cache, log, graphql)
# ✓ Variables (SQL, Handlebars, GraphQL)
# ✓ Pipelines (reusable middleware chains)
# ✓ Routes (GET, POST, PUT, DELETE)
# ✓ JQ transformations
# ✓ Handlebars templating (partials, layouts, inline blocks)
# ✓ Postgres/SQL with modern inline syntax: pg([.param])
# ✓ Lua scripting (executeSql, getEnv, setFlag)
# ✓ Result routing (ok, validationError, authError, sqlError)
# ✓ Validation (string, number, email, rules)
# ✓ Authentication (login, register, logout, required, optional)
# ✓ Caching (TTL, custom keyTemplate)
# ✓ Logging and debugging
# ✓ Cookies (read and set)
# ✓ HTTP Fetch with inline syntax: fetch("url")
# ✓ GraphQL with inline syntax: graphql({ var: .value })
# ✓ Tags & Feature Flags (@env, @flag, @async, @result)
# ✓ Async/Join (parallel execution)
# ✓ Tests (let variables, selectors, multiple assertions)
#
# For more examples, see comprehensive_test.wp