update class demo with custom constructor

This commit is contained in:
forehalo 2021-09-24 13:00:35 +08:00 committed by LongYinan
parent 0d018a5470
commit ee7a146ea1
6 changed files with 23 additions and 8 deletions

View file

@ -74,7 +74,7 @@ impl NapiFn {
Some(_) => "",
None => "static",
},
crate::FnKind::Constructor => "constructor",
crate::FnKind::Constructor => "",
crate::FnKind::Getter => "get",
crate::FnKind::Setter => "set",
}

View file

@ -542,6 +542,8 @@ fn napi_fn_from_decl(
.trim_start_matches("set_")
.to_case(Case::Camel)
}
} else if opts.constructor().is_some() {
"constructor".to_owned()
} else {
opts.js_name().map_or_else(
|| ident.to_string().to_case(Case::Camel),

View file

@ -28,9 +28,9 @@ Generated by [AVA](https://avajs.dev).
export function concatLatin1(s: Latin1String): string␊
export class Animal {␊
readonly kind: Kind␊
name: string␊
constructor(kind: Kind, name: string)␊
static new(kind: Kind, name: string): Animal␊
get name(): string␊
set name(name: string)␊
whoami(): string␊
}␊
`

View file

@ -18,8 +18,8 @@ export function concatUtf16(s: Utf16String): Utf16String
export function concatLatin1(s: Latin1String): string
export class Animal {
readonly kind: Kind
name: string
constructor(kind: Kind, name: string)
static new(kind: Kind, name: string): Animal
get name(): string
set name(name: string)
whoami(): string
}

View file

@ -2,20 +2,33 @@ use napi::bindgen_prelude::*;
use crate::r#enum::Kind;
#[napi(constructor)]
/// `constructor` option for `struct` requires all fields to be public,
/// otherwise tag impl fn as constructor
/// #[napi(constructor)]
#[napi]
pub struct Animal {
#[napi(readonly)]
pub kind: Kind,
pub name: String,
name: String,
}
#[napi]
impl Animal {
#[napi]
#[napi(constructor)]
pub fn new(kind: Kind, name: String) -> Self {
Animal { kind, name }
}
#[napi(getter)]
pub fn get_name(&self) -> &str {
self.name.as_str()
}
#[napi(setter)]
pub fn set_name(&mut self, name: String) {
self.name = name;
}
#[napi]
pub fn whoami(&self) -> String {
match self.kind {