fix(napi-derive): return Result type in Constructor and Factory

This commit is contained in:
LongYinan 2021-11-06 21:48:18 +08:00
parent 44040e3bfe
commit e9ab2192da
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
7 changed files with 62 additions and 5 deletions

View file

@ -244,9 +244,17 @@ impl NapiFn {
if let Some(ty) = &self.ret {
if self.kind == FnKind::Constructor {
quote! { cb.construct(#js_name, #ret) }
if self.is_ret_result {
quote! { cb.construct(#js_name, #ret?) }
} else {
quote! { cb.construct(#js_name, #ret) }
}
} else if self.kind == FnKind::Factory {
quote! { cb.factory(#js_name, #ret) }
if self.is_ret_result {
quote! { cb.factory(#js_name, #ret?) }
} else {
quote! { cb.factory(#js_name, #ret) }
}
} else if self.is_ret_result {
if self.is_async {
quote! {

View file

@ -234,9 +234,8 @@ fn extract_callback_trait_types(
fn extract_result_ty(ty: &syn::Type) -> BindgenResult<Option<syn::Type>> {
match ty {
syn::Type::Path(syn::TypePath { qself: None, path }) if path.segments.len() == 1 => {
let segment = path.segments.first().unwrap();
syn::Type::Path(syn::TypePath { qself: None, path }) => {
let segment = path.segments.last().unwrap();
if segment.ident != "Result" {
Ok(None)
} else {

View file

@ -61,6 +61,12 @@ Generated by [AVA](https://avajs.dev).
export class Blake2BKey {␊
}␊
export class Context {␊
constructor()␊
static withData(data: string): Context␊
method(): string␊
}␊
export class ClassWithFactory {␊
name: string␊
static withName(name: string): ClassWithFactory␊

View file

@ -17,6 +17,7 @@ import {
Kind,
ClassWithFactory,
CustomNumEnum,
Context,
enumToI32,
listObjKeys,
createObj,
@ -96,6 +97,16 @@ test('class factory', (t) => {
t.is(doge.name, '旺财')
})
test('class constructor return Result', (t) => {
const c = new Context()
t.is(c.method(), 'not empty')
})
test('class Factory return Result', (t) => {
const c = Context.withData('not empty')
t.is(c.method(), 'not empty')
})
test('callback', (t) => {
getCwd((cwd) => {
t.is(cwd, process.cwd())

View file

@ -50,6 +50,12 @@ export class Blake2BHasher {
}
export class Blake2BKey {
}
export class Context {
constructor()
static withData(data: string): Context
method(): string
}
export class ClassWithFactory {
name: string

View file

@ -1,4 +1,5 @@
use napi::bindgen_prelude::*;
use napi::Result;
use crate::r#enum::Kind;
@ -75,3 +76,29 @@ impl Blake2bKey {
self.0
}
}
#[napi]
pub struct Context {
data: String,
}
// Test for return `napi::Result` and `Result`
#[napi]
impl Context {
#[napi(constructor)]
pub fn new() -> napi::Result<Self> {
Ok(Self {
data: "not empty".into(),
})
}
#[napi(factory)]
pub fn with_data(data: String) -> Result<Self> {
Ok(Self { data })
}
#[napi]
pub fn method(&self) -> String {
self.data.clone()
}
}