feat(napi): support static class factory
This commit is contained in:
parent
e74fe2fb94
commit
e78cdd3c22
15 changed files with 150 additions and 15 deletions
examples/napi
|
@ -48,9 +48,14 @@ Generated by [AVA](https://avajs.dev).
|
|||
export class Animal {␊
|
||||
readonly kind: Kind␊
|
||||
constructor(kind: Kind, name: string)␊
|
||||
static withKind(kind: Kind): Animal␊
|
||||
get name(): string␊
|
||||
set name(name: string)␊
|
||||
whoami(): string␊
|
||||
static getDogKind(): Kind␊
|
||||
}␊
|
||||
export class ClassWithFactory {␊
|
||||
name: string␊
|
||||
static withName(name: string): ClassWithFactory␊
|
||||
}␊
|
||||
`
|
||||
|
|
Binary file not shown.
|
@ -15,6 +15,7 @@ import {
|
|||
getCwd,
|
||||
Animal,
|
||||
Kind,
|
||||
ClassWithFactory,
|
||||
CustomNumEnum,
|
||||
enumToI32,
|
||||
listObjKeys,
|
||||
|
@ -81,6 +82,20 @@ test('class', (t) => {
|
|||
t.is(dog.name, '可乐')
|
||||
})
|
||||
|
||||
test('class factory', (t) => {
|
||||
const duck = ClassWithFactory.withName('Default')
|
||||
t.is(duck.name, 'Default')
|
||||
|
||||
duck.name = '周黑鸭'
|
||||
t.is(duck.name, '周黑鸭')
|
||||
|
||||
const doge = Animal.withKind(Kind.Dog)
|
||||
t.is(doge.name, 'Default')
|
||||
|
||||
doge.name = '旺财'
|
||||
t.is(doge.name, '旺财')
|
||||
})
|
||||
|
||||
test('callback', (t) => {
|
||||
getCwd((cwd) => {
|
||||
t.is(cwd, process.cwd())
|
||||
|
|
5
examples/napi/index.d.ts
vendored
5
examples/napi/index.d.ts
vendored
|
@ -38,8 +38,13 @@ export function getBuffer(): Buffer
|
|||
export class Animal {
|
||||
readonly kind: Kind
|
||||
constructor(kind: Kind, name: string)
|
||||
static withKind(kind: Kind): Animal
|
||||
get name(): string
|
||||
set name(name: string)
|
||||
whoami(): string
|
||||
static getDogKind(): Kind
|
||||
}
|
||||
export class ClassWithFactory {
|
||||
name: string
|
||||
static withName(name: string): ClassWithFactory
|
||||
}
|
||||
|
|
|
@ -19,6 +19,14 @@ impl Animal {
|
|||
Animal { kind, name }
|
||||
}
|
||||
|
||||
#[napi(factory)]
|
||||
pub fn with_kind(kind: Kind) -> Self {
|
||||
Animal {
|
||||
kind,
|
||||
name: "Default".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[napi(getter)]
|
||||
pub fn get_name(&self) -> &str {
|
||||
self.name.as_str()
|
||||
|
|
14
examples/napi/src/class_factory.rs
Normal file
14
examples/napi/src/class_factory.rs
Normal file
|
@ -0,0 +1,14 @@
|
|||
use napi::bindgen_prelude::*;
|
||||
|
||||
#[napi]
|
||||
pub struct ClassWithFactory {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[napi]
|
||||
impl ClassWithFactory {
|
||||
#[napi(factory)]
|
||||
pub fn with_name(name: String) -> Self {
|
||||
Self { name }
|
||||
}
|
||||
}
|
|
@ -7,6 +7,7 @@ mod array;
|
|||
mod r#async;
|
||||
mod callback;
|
||||
mod class;
|
||||
mod class_factory;
|
||||
mod either;
|
||||
mod r#enum;
|
||||
mod error;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue