rapid-web 0.4.9

A simple Rust server for the Rapid framework.
Documentation
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
use super::{
	convert::{convert_all_types_in_path, TypescriptConverter, TypescriptType},
	util::{
		extract_handler_types, get_handler_type, get_output_type_alias, get_route_key, is_dynamic_route, remove_last_occurrence, space,
		HandlerRequestType, TypeClass, GENERATED_TS_FILE_MESSAGE,
	},
};
use crate::util::validate_route_handler;
use std::{
	fs::{File, OpenOptions},
	io::prelude::*,
	path::PathBuf,
};
use walkdir::WalkDir;

#[derive(Debug, Clone, PartialEq)]
pub enum Handler {
	Query(TypedQueryHandler),
	Mutation(TypedMutationHandler),
}

#[derive(Debug, Clone, PartialEq)]
pub struct RouteKey {
	pub key: String,
	pub value: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TypedQueryHandler {
	pub request_type: HandlerRequestType,
	pub path: Option<TypescriptType>,
	pub query_params: Option<TypescriptType>,
	pub output_type: TypescriptType,
	pub route_key: RouteKey,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TypedMutationHandler {
	pub request_type: HandlerRequestType,
	pub query_params: Option<TypescriptType>,
	pub path: Option<TypescriptType>,
	pub input_type: Option<TypescriptType>,
	pub output_type: TypescriptType,
	pub route_key: RouteKey,
}

/// Function for generating typescript types from a rapid routes directory
pub fn generate_handler_types(routes_path: PathBuf, converter: &mut TypescriptConverter) -> Vec<Handler> {
	let mut handlers: Vec<Handler> = Vec::new();

	let routes_dir = routes_path;

	for route_file in WalkDir::new(routes_dir.clone()) {
		let entry = match route_file {
			Ok(val) => val,
			Err(e) => panic!("An error occurred what attempting to parse directory: {}", e),
		};

		// We only want to handle route files and no directories (the walkDir crate auto iterates through nested dirs)
		if entry.path().is_dir() {
			continue;
		}

		// We also want to make sure that we exit if we find a mod.rs file or a middleware file
		let file_name = entry.file_name();

		// Make sure we ignore middleware and mod files from route handler generation
		if file_name == "_middleware.rs" || file_name == "mod.rs" {
			continue;
		}

		// Create a reference to the current route file and grab its contents as a string
		let mut file = File::open(&entry.path()).unwrap();
		let mut route_file_contents = String::new();
		file.read_to_string(&mut route_file_contents).unwrap();

		// We also want to exit early if the route is invalid
		if !validate_route_handler(&route_file_contents) {
			continue;
		}

		let parsed_route_dir = entry
			.path()
			.to_str()
			.unwrap_or("/")
			.to_string()
			.replace(routes_dir.to_str().unwrap_or("src/routes"), "")
			.replace(".rs", "");

		let route_key = RouteKey {
			key: get_route_key(parsed_route_dir.clone(), &route_file_contents),
			value: parsed_route_dir,
		};

		let handler_types = match extract_handler_types(&route_file_contents) {
			Some(val) => {
				if val.len() > 0 {
					val
				} else {
					continue;
				}
			}
			None => continue,
		};

		let mut query_params: Option<TypescriptType> = None;
		let mut body_type: Option<TypescriptType> = None;
		let mut path: Option<TypescriptType> = None;
		let output_type: TypescriptType = get_output_type_alias(&route_file_contents);
		let request_type = handler_types[0].as_ref().unwrap().handler_type.clone();

		for typed in handler_types {
			let rust_type = match typed {
				Some(val) => val,
				None => continue,
			};

			let converted_type = match rust_type.type_value {
				Some(val) => converter.convert_primitive(val),
				None => TypescriptType {
					typescript_type: String::from("any"),
					is_optional: false,
				},
			};

			match rust_type.class {
				Some(TypeClass::InputBody) => body_type = Some(converted_type),
				Some(TypeClass::QueryParam) => query_params = Some(converted_type),
				Some(TypeClass::Path) => path = Some(converted_type),
				_ => continue,
			}
		}

		match request_type {
			HandlerRequestType::Get => {
				handlers.push(Handler::Query(TypedQueryHandler {
					request_type,
					path,
					query_params,
					output_type,
					route_key,
				}));
			}
			HandlerRequestType::Query => {
				handlers.push(Handler::Query(TypedQueryHandler {
					request_type,
					path,
					query_params,
					output_type,
					route_key,
				}));
			}
			_ => {
				handlers.push(Handler::Mutation(TypedMutationHandler {
					request_type,
					query_params,
					path,
					input_type: body_type,
					output_type,
					route_key,
				}));
			}
		}
	}

	handlers
}

pub fn create_typescript_types(out_dir: PathBuf, route_dir: PathBuf, type_generation_dir: PathBuf) {
	// Create a new bindings.ts file to store all of our generated types
	let file = OpenOptions::new()
		.write(true)
		.create(true)
		.truncate(true)
		.open(format!("{}/bindings.ts", out_dir.as_os_str().to_str().unwrap()))
		.unwrap();

	// Init our typescript converter
	let mut converter = TypescriptConverter::new(true, "".to_string(), true, 4, file);

	let handlers = generate_handler_types(route_dir.clone(), &mut converter);

	// Early exit without doing anything if we did not detect any handlers
	if handlers.len() < 1 {
		return;
	}

	let routes = generate_routes(route_dir.to_str().unwrap());

	// Init our a queries and mutations keys in the handlers interface
	let mut queries_ts = String::from("{");
	let mut mutations_ts = String::from("{");

	// TODO: convert every type in the entire project to a typescript type
	// Make sure that we skip the routes directory when converting types

	// Convert every type in project to a typescript type (this is so that any used types in the route handlers generated above do not error out)
	convert_all_types_in_path(type_generation_dir.to_str().unwrap(), &mut converter);

	// Loop through every handler and generate the typescript type for it
	for handler in handlers {
		match handler {
			Handler::Query(query) => {
				let mut ts_type = format!("\n\t\t{}: {{\n", query.route_key.key);
				let route_path = query.route_key.value;
				let is_dynamic_route_path = is_dynamic_route(&route_path);

				let spacing = space(2);
				let request_type = match query.request_type {
					HandlerRequestType::Post => "post",
					HandlerRequestType::Put => "put",
					HandlerRequestType::Delete => "delete",
					HandlerRequestType::Get => "get",
					HandlerRequestType::Patch => "patch",
					HandlerRequestType::Query => "query",
					HandlerRequestType::Mutation => "mutation",
				};

				if let Some(query_params_type) = query.query_params {
					let query_type = query_params_type.typescript_type;
					if converter.converted_types.contains(&query_type) {
						let query_params = format!("\t\t\tquery_params: {}", query_type);
						ts_type.push_str(&format!("{}{}\n", spacing, query_params));
					} else {
						let query_params = format!("\t\t\tquery_params: {}", "any");
						ts_type.push_str(&format!("{}{}\n", spacing, query_params));
					}
				}

				if let Some(dynamic_path_type) = query.path {
					let path_type = dynamic_path_type.typescript_type;
					// If we found a path then that means this route handler is dynamic so lets also push a isDynamic type to the handler schema
					if converter.converted_types.contains(&path_type) {
						let path = format!("\t\t\tpath: {}", path_type);
						ts_type.push_str(&format!("{}{}\n", spacing, path));
					} else {
						let path = format!("\t\t\tpath: {}", "any");
						ts_type.push_str(&format!("{}{}\n", spacing, path));
					}
				}

				let output_body = format!("\t\t\toutput: {}", query.output_type.typescript_type);
				ts_type.push_str(&format!("{}{}\n", spacing, output_body));

				let request_type = format!("\t\t\ttype: '{}'", request_type);
				ts_type.push_str(&format!("{}{}\n", spacing, request_type));

				let dynamic_type = format!("\t\t\tisDynamic: {}", is_dynamic_route_path);
				ts_type.push_str(&format!("{}{}\n", spacing, dynamic_type));

				ts_type.push_str(&format!("\t\t}},\n"));

				queries_ts.push_str(&ts_type);
			}
			Handler::Mutation(mutation) => {
				let mut ts_type = format!("\n\t\t{}: {{\n", mutation.route_key.key);
				let route_path = mutation.route_key.value;
				let spacing = space(2);
				let is_dynamic_route_path = is_dynamic_route(&route_path);
				let request_type = match mutation.request_type {
					HandlerRequestType::Post => "post",
					HandlerRequestType::Put => "put",
					HandlerRequestType::Delete => "delete",
					HandlerRequestType::Get => "get",
					HandlerRequestType::Patch => "patch",
					HandlerRequestType::Query => "query",
					HandlerRequestType::Mutation => "mutation",
				};

				if let Some(query_params_type) = mutation.query_params {
					// We only want to add query params if the TS type has already been generated
					let query_type = query_params_type.typescript_type;
					if converter.converted_types.contains(&query_type) {
						let query_params = format!("\t\t\tquery_params: {}", query_type);
						ts_type.push_str(&format!("{}{}\n", spacing, query_params));
					} else {
						let query_params = format!("\t\t\tquery_params: {}", "any");
						ts_type.push_str(&format!("{}{}\n", spacing, query_params));
					}
				}

				if let Some(dynamic_path_type) = mutation.path {
					let path_type = dynamic_path_type.typescript_type;
					if converter.converted_types.contains(&path_type) {
						let path = format!("\t\t\tpath: {}", path_type);
						ts_type.push_str(&format!("{}{}\n", spacing, path));
					} else {
						let path = format!("\t\t\tpath: {}", "any");
						ts_type.push_str(&format!("{}{}\n", spacing, path));
					}
				}

				if let Some(input_body_type) = mutation.input_type {
					let input_body = input_body_type.typescript_type;
					if converter.converted_types.contains(&input_body) {
						let body = format!("\t\t\tinput: {}", input_body);
						ts_type.push_str(&format!("{}{}\n", spacing, body));
					} else {
						let body = format!("\t\t\tinput: {}", "any");
						ts_type.push_str(&format!("{}{}\n", spacing, body));
					}
				}

				// Output body defaults to any (we currently do not support typesafe output types)
				// TODO: when we support output types, lets change this!
				let output_body = format!("\t\t\toutput: {}", mutation.output_type.typescript_type);
				ts_type.push_str(&format!("{}{}\n", spacing, output_body));

				let request_type = format!("\t\t\ttype: '{}'", request_type);
				ts_type.push_str(&format!("{}{}\n", spacing, request_type));

				let dynamic_type = format!("\t\t\tisDynamic: {}", is_dynamic_route_path);
				ts_type.push_str(&format!("{}{}\n", spacing, dynamic_type));

				ts_type.push_str(&format!("\t\t}}\n"));

				mutations_ts.push_str(&ts_type);
			}
		}
	}

	queries_ts.push_str("\t},");

	// Only have tabs when types are present
	if mutations_ts.len() < 2 {
		mutations_ts.push_str("},");
	} else {
		mutations_ts.push_str("\t},");
	}

	let mut handlers_interface = format!("\n\nexport interface Handlers {{\n");

	handlers_interface.push_str(&format!("\tqueries: {}\n", queries_ts));
	handlers_interface.push_str(&format!("\tmutations: {}\n", mutations_ts));
	handlers_interface.push_str("}");

	// Add all the route handler types for mutations and queries
	converter.generate(Some(GENERATED_TS_FILE_MESSAGE));
	converter.generate(Some(&handlers_interface));
	converter.generate(Some(&routes));

	// Write the new types to the bindings file
	converter.generate(None);
}

/// Function for generating a route handler object for use on the client
/// It will output something similar to the following:
/// const routes = {
/// 	index: '/'
/// }
///
pub fn generate_routes(routes_dir: &str) -> String {
	let mut typescript_object = String::from("\n\nexport const routes = {");

	for route_file in WalkDir::new(routes_dir.clone()) {
		let entry = match route_file {
			Ok(val) => val,
			Err(e) => panic!("An error occurred what attempting to parse directory: {}", e),
		};

		// We only want to handle route files and no directories (the walkDir crate auto iterates through nested dirs)
		if entry.path().is_dir() {
			continue;
		}

		// Create a reference to the current route file and grab its contents as a string
		let mut file = File::open(&entry.path()).unwrap();
		let mut route_file_contents = String::new();
		file.read_to_string(&mut route_file_contents).unwrap();

		// We also want to exit early if the route is invalid
		if !validate_route_handler(&route_file_contents) {
			continue;
		}

		let file_name = entry.file_name();

		// Make sure we ignore middleware and mod files from route generation
		if file_name == "_middleware.rs" || file_name == "mod.rs" {
			continue;
		}

		let parsed_route_dir = entry
			.path()
			.to_str()
			.unwrap_or("/")
			.to_string()
			.replace(routes_dir, "")
			.replace(".rs", "");

		let handler_type = match get_handler_type(&route_file_contents) {
			Some(name) => name,
			None => String::from("get"),
		};

		// Construct our routes object
		let route_key = RouteKey {
			key: get_route_key(parsed_route_dir.clone(), &route_file_contents),
			value: remove_last_occurrence(&parsed_route_dir, "index"),
		};

		let mut route = format!("\n\t{}: {{\n", route_key.key);
		// Add the url
		route.push_str(&format!("\t\turl: '{url}',\n", url = route_key.value));
		// Add the route type
		route.push_str(&format!("\t\ttype: '{route_type}',\n", route_type = handler_type));
		// Make sure we close off the new route...
		route.push_str("\t},");
		typescript_object.push_str(&route);
	}

	// Once we are done we want to close off the object
	typescript_object.push_str("\n} as const");

	typescript_object
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_generate_handler_types() {
		let out_dir = PathBuf::from("tests/mocks/temp");
		let bindings_file = OpenOptions::new()
		.write(true)
		.create(true)
		.truncate(true)
		.open(format!("{}/bindings.ts", out_dir.as_os_str().to_str().unwrap()))
		.unwrap();
		let routes = generate_handler_types(PathBuf::from("tests/mocks/files"), &mut TypescriptConverter::new(true, "".to_string(), true, 4, bindings_file));

		let mut expected_handlers: Vec<Handler> = Vec::new();

		let hello_handler = Handler::Query(TypedQueryHandler {
			request_type: HandlerRequestType::Query,
			path: None,
			query_params: None,
			output_type: TypescriptType {
				typescript_type: String::from("any"),
				is_optional: false,
			},
			route_key: RouteKey {
				key: String::from("hello"),
				value: String::from("/hello"),
			},
		});

		let mutation_handler = Handler::Mutation(TypedMutationHandler {
			request_type: HandlerRequestType::Mutation,
			query_params: None,
			path: None,
			input_type: None,
			output_type: TypescriptType {
				typescript_type: String::from("any"),
				is_optional: false,
			},
			route_key: RouteKey {
				key: String::from("mutation"),
				value: String::from("/mutation"),
			},
		});

		expected_handlers.push(mutation_handler);
		expected_handlers.push(hello_handler);

		assert_eq!(routes, expected_handlers);
	}

	#[test]
	fn test_create_typescript_types() {
		let out_dir = PathBuf::from("tests/mocks/temp");
		let route_dir = PathBuf::from("tests/mocks/files");
		let type_generation_dir = PathBuf::from("tests/mocks/files");

		create_typescript_types(out_dir, route_dir, type_generation_dir);

		let mut file = File::open("tests/mocks/temp/bindings.ts").unwrap();
		let mut contents = String::new();
		file.read_to_string(&mut contents).unwrap();

		// Delete the temp file
		std::fs::remove_file("tests/mocks/temp/bindings.ts").unwrap();

		const _: &str = "// @generated automatically by Rapid-web (https://rapid.cincinnati.ventures). DO NOT CHANGE OR EDIT THIS FILE!

export interface Handlers {
	queries: {
		hello: {
				output: any
				type: 'query'
				isDynamic: false
		},
	},
	mutations: {
		mutation: {
				output: any
				type: 'mutation'
				isDynamic: false
		}
	},
}

export const routes = {
	mutation: {
		url: '/mutation',
		type: 'mutation',
	},
	hello: {
		url: '/hello',
		type: 'query',
	},
} as const
";

		// TODO: fix this test - has some issues with writing to files
	}

	#[test]
	fn test_generate_routes() {
		let routes = generate_routes("tests/mocks/files");
		const EXPECTED: &str = "\n\nexport const routes = {\n\tmutation: {\n\t\turl: '/mutation',\n\t\ttype: 'mutation',\n\t},\n\thello: {\n\t\turl: '/hello',\n\t\ttype: 'query',\n\t},\n} as const";

		assert_eq!(routes, EXPECTED);
	}
}