Skip to content

Commit

Permalink
Core: Add support for parameter assignment pattern (#38)
Browse files Browse the repository at this point in the history
* do it

* version bump
  • Loading branch information
lucasavila00 authored Sep 10, 2023
1 parent 6d0b071 commit 16daf54
Show file tree
Hide file tree
Showing 33 changed files with 446 additions and 184 deletions.
10 changes: 10 additions & 0 deletions examples/minimal-react/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# @examples/minimal-react

## 10.38.5

### Patch Changes

- Updated dependencies
- @beff/client@0.0.8
- @beff/hono@0.0.8
- @beff/cli@0.0.8
- @beff/react@0.0.8

## 10.38.4

### Patch Changes
Expand Down
10 changes: 5 additions & 5 deletions examples/minimal-react/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@examples/minimal-react",
"private": true,
"version": "10.38.4",
"version": "10.38.5",
"workspaces": [
"client",
"server"
Expand All @@ -26,10 +26,10 @@
"wait-port": "^1.0.1"
},
"dependencies": {
"@beff/cli": "workspace:^0.0.7",
"@beff/client": "workspace:^0.0.7",
"@beff/hono": "workspace:^0.0.7",
"@beff/react": "workspace:^0.0.7",
"@beff/cli": "workspace:^0.0.8",
"@beff/client": "workspace:^0.0.8",
"@beff/hono": "workspace:^0.0.8",
"@beff/react": "workspace:^0.0.8",
"@hono/node-server": "^1.1.1",
"@tanstack/react-query": "^4.33.0",
"@types/node": "^20.5.7",
Expand Down
8 changes: 8 additions & 0 deletions examples/node-server/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# node-server

## 1.0.4

### Patch Changes

- Updated dependencies
- @beff/hono@0.0.8
- @beff/cli@0.0.8

## 1.0.3

### Patch Changes
Expand Down
6 changes: 3 additions & 3 deletions examples/node-server/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "node-server",
"version": "1.0.3",
"version": "1.0.4",
"description": "",
"main": "index.js",
"scripts": {
Expand All @@ -12,8 +12,8 @@
"author": "",
"license": "ISC",
"dependencies": {
"@beff/cli": "workspace:^0.0.7",
"@beff/hono": "workspace:^0.0.7",
"@beff/cli": "workspace:^0.0.8",
"@beff/hono": "workspace:^0.0.8",
"@hono/node-server": "^1.1.1",
"esbuild": "^0.19.2",
"vitest": "^0.34.3"
Expand Down
7 changes: 7 additions & 0 deletions examples/standalone-parser/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# node-server

## 1.0.5

### Patch Changes

- Updated dependencies
- @beff/cli@0.0.8

## 1.0.4

### Patch Changes
Expand Down
4 changes: 2 additions & 2 deletions examples/standalone-parser/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "standalone-parser",
"version": "1.0.4",
"version": "1.0.5",
"description": "",
"main": "index.js",
"scripts": {
Expand All @@ -11,7 +11,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@beff/cli": "workspace:^0.0.7",
"@beff/cli": "workspace:^0.0.8",
"vitest": "^0.34.3"
}
}
6 changes: 6 additions & 0 deletions packages/beff-cli/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# @beff/cli

## 0.0.8

### Patch Changes

- Support for optional parameters

## 0.0.7

### Patch Changes
Expand Down
2 changes: 1 addition & 1 deletion packages/beff-cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@beff/cli",
"version": "0.0.7",
"version": "0.0.8",
"description": "",
"bin": {
"beff": "./bin/index.js"
Expand Down
8 changes: 8 additions & 0 deletions packages/beff-client/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# @beff/client

## 0.0.8

### Patch Changes

- Support for optional parameters
- Updated dependencies
- @beff/cli@0.0.8

## 0.0.7

### Patch Changes
Expand Down
4 changes: 2 additions & 2 deletions packages/beff-client/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@beff/client",
"version": "0.0.7",
"version": "0.0.8",
"description": "",
"main": "dist/cjs/index.js",
"scripts": {
Expand All @@ -18,7 +18,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"@beff/cli": "workspace:^0.0.7"
"@beff/cli": "workspace:^0.0.8"
},
"devDependencies": {
"typescript": "^5.2.2"
Expand Down
20 changes: 14 additions & 6 deletions packages/beff-client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,25 @@ export class BffRequest {
break;
}
case "query": {
if (!hasAddedQueryParams) {
path += "?";
hasAddedQueryParams = true;
path += `${metadata.name}=${param}`;
if (!metadata.required && param == null) {
// skip optional query params
} else {
path += `&${metadata.name}=${param}`;
if (!hasAddedQueryParams) {
path += "?";
hasAddedQueryParams = true;
path += `${metadata.name}=${param}`;
} else {
path += `&${metadata.name}=${param}`;
}
}
break;
}
case "header": {
init.headers[metadata.name] = String(param);
if (!metadata.required && param == null) {
// skip optional headers
} else {
init.headers[metadata.name] = String(param);
}
break;
}
case "body": {
Expand Down
41 changes: 36 additions & 5 deletions packages/beff-core/src/api_extractor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,36 @@ pub enum HandlerParameter {
Context(Span),
}

impl HandlerParameter {
pub fn make_optional(self: HandlerParameter) -> HandlerParameter {
match self {
HandlerParameter::PathOrQueryOrBody {
schema,
description,
span,
..
} => HandlerParameter::PathOrQueryOrBody {
schema,
required: false,
description,
span,
},
HandlerParameter::Header {
span,
schema,
description,
..
} => HandlerParameter::Header {
span,
schema,
required: false,
description,
},
HandlerParameter::Context(_) => self,
}
}
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum MethodKind {
Get(Span),
Expand Down Expand Up @@ -477,7 +507,7 @@ impl<'a, R: FileManager> ExtractExportDefaultVisitor<'a, R> {
&mut self,
param: &Pat,
parent_span: &Span,
) -> Result<Vec<(String, HandlerParameter)>> {
) -> Result<(String, HandlerParameter)> {
match param {
Pat::Ident(BindingIdent { id, type_ann }) => {
if type_ann.is_none() {
Expand All @@ -492,12 +522,15 @@ impl<'a, R: FileManager> ExtractExportDefaultVisitor<'a, R> {
comments.and_then(|it| self.parse_description_comment(it, &id.span));
let ty = self.assert_and_extract_type_from_ann(type_ann, &id.span);
let param = self.parse_parameter_type(&ty, !id.optional, description, &id.span)?;
Ok(vec![(id.sym.to_string(), param)])
Ok((id.sym.to_string(), param))
}
Pat::Assign(AssignPat { span, left, .. }) => {
let (name, ty) = self.parse_arrow_parameter(left, span)?;
Ok((name, ty.make_optional()))
}
Pat::Rest(RestPat { span, .. })
| Pat::Array(ArrayPat { span, .. })
| Pat::Object(ObjectPat { span, .. })
| Pat::Assign(AssignPat { span, .. })
| Pat::Invalid(Invalid { span, .. }) => {
self.error(span, DiagnosticInfoMessage::ParameterPatternNotSupported)
}
Expand Down Expand Up @@ -557,7 +590,6 @@ impl<'a, R: FileManager> ExtractExportDefaultVisitor<'a, R> {
.iter()
.map(|it| self.parse_arrow_parameter(&it.pat, parent_span))
.collect::<Result<Vec<_>>>()?;
let parameters = parameters.into_iter().flatten().collect();
let e = FnHandler {
method_kind: self.parse_method_kind(key)?,
parameters,
Expand Down Expand Up @@ -625,7 +657,6 @@ impl<'a, R: FileManager> ExtractExportDefaultVisitor<'a, R> {
.map(|it| self.parse_arrow_parameter(it, parent_span))
.collect::<Result<Vec<_>>>()?
.into_iter()
.flatten()
.collect(),
summary: endpoint_comments.summary,
description: endpoint_comments.description,
Expand Down
26 changes: 23 additions & 3 deletions packages/beff-core/src/print/coercer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{swc_builder::SwcBuilder, ast::json_schema::JsonSchema};
use crate::{ast::json_schema::JsonSchema, swc_builder::SwcBuilder};
use swc_common::DUMMY_SP;
use swc_ecma_ast::{
BindingIdent, BlockStmt, CallExpr, Callee, Expr, ExprOrSpread, FnExpr, Function, Ident, Param,
Expand All @@ -25,11 +25,31 @@ fn coerce_primitive(value: Expr, p: &str) -> Expr {
})
}

fn coercion_noop(value: Expr) -> Expr {
let decoder_ref_fn = Ident {
span: DUMMY_SP,
sym: format!("CoercionNoop").into(),
optional: false,
};
let callee = Callee::Expr(Expr::Ident(decoder_ref_fn).into());
Expr::Call(CallExpr {
span: DUMMY_SP,
callee: callee,
args: vec![ExprOrSpread {
spread: None,
expr: value.into(),
}],
type_args: None,
})
}

struct CoercerFnGenerator {}
impl CoercerFnGenerator {
fn coerce_schema(&mut self, schema: &JsonSchema, value_ref: &Expr, depth: usize) -> Expr {
match schema {
JsonSchema::Null | JsonSchema::Const(_) | JsonSchema::Any => value_ref.clone(),
JsonSchema::Null | JsonSchema::Const(_) | JsonSchema::Any => {
coercion_noop(value_ref.clone())
}
JsonSchema::Boolean => coerce_primitive(value_ref.clone(), "boolean"),
JsonSchema::String => coerce_primitive(value_ref.clone(), "string"),
JsonSchema::StringWithFormat(_) => coerce_primitive(value_ref.clone(), "string"),
Expand Down Expand Up @@ -90,7 +110,7 @@ impl CoercerFnGenerator {
let input = SwcBuilder::input_expr();
let stmts = vec![Stmt::Return(ReturnStmt {
span: DUMMY_SP,
arg: Some(Box::new(self.coerce_schema(schema, &input, depth))),
arg: Some(self.coerce_schema(schema, &input, depth).into()),
})];

Function {
Expand Down
9 changes: 9 additions & 0 deletions packages/beff-hono/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# @beff/hono

## 0.0.8

### Patch Changes

- Support for optional parameters
- Updated dependencies
- @beff/client@0.0.8
- @beff/cli@0.0.8

## 0.0.7

### Patch Changes
Expand Down
6 changes: 3 additions & 3 deletions packages/beff-hono/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@beff/hono",
"version": "0.0.7",
"version": "0.0.8",
"description": "",
"main": "dist/cjs/index.js",
"scripts": {
Expand All @@ -18,8 +18,8 @@
"author": "",
"license": "ISC",
"dependencies": {
"@beff/cli": "workspace:^0.0.7",
"@beff/client": "workspace:^0.0.7",
"@beff/cli": "workspace:^0.0.8",
"@beff/client": "workspace:^0.0.8",
"hono": "^3.5.6",
"vitest": "^0.34.3"
},
Expand Down
18 changes: 1 addition & 17 deletions packages/beff-hono/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ const redocTemplate = (baseUrl: string) => `
`;

const coerce = (coercer: any, value: any): any => {
return coercer(value);
return coercer(value).data;
};

const toHonoPattern = (pattern: string): string => {
Expand Down Expand Up @@ -115,23 +115,7 @@ const prettyPrintErrorMessage = (it: DecodeError): string => {
}
};

type CoercionFailure = {
__isCoercionFailure: true;
original: unknown;
};

const isCoercionFailure = (it: unknown): it is CoercionFailure => {
return (
typeof it === "object" &&
it != null &&
"__isCoercionFailure" in it &&
Boolean(it?.__isCoercionFailure)
);
};
const prettyPrintValue = (it: unknown): string => {
if (isCoercionFailure(it)) {
return prettyPrintValue(it.original);
}
if (typeof it === "string") {
return `"${it}"`;
}
Expand Down
8 changes: 8 additions & 0 deletions packages/beff-react/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# @beff/react

## 0.0.8

### Patch Changes

- Support for optional parameters
- Updated dependencies
- @beff/client@0.0.8

## 0.0.7

### Patch Changes
Expand Down
Loading

0 comments on commit 16daf54

Please sign in to comment.