Skip to content

Commit

Permalink
Generate isInstance type guard for every CustomResource
Browse files Browse the repository at this point in the history
`Resource.isInstance` is a static method that provides a type guard
allowing users to check whether an arbitrary object is a `Resource`.

This commit implements this function for all implementations of
`Resource`. So, e.g., `s3.Bucket.isInstance(foo)` is a type guard for
`Bucket`.
  • Loading branch information
hausdorff committed Jun 4, 2019
1 parent 321ad3f commit 7ace3e9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ This CHANGELOG details important changes made in each version of the

## v0.18.3 (Unreleased)

### Improvements

- Automatically generate `isInstance` type guards for implementations of `Resource`.

## v0.18.2 (Released May 28th, 2019)

- Improved the package `README` file to reflect usage of the `@pulumi/terraform`
Expand Down
17 changes: 16 additions & 1 deletion pkg/tfgen/generate_nodejs.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,21 @@ func (g *nodeJSGenerator) emitResourceType(mod *module, res *resourceType) (stri
w.Writefmtln("")
}

w.Writefmtln(" /** @internal */")
w.Writefmtln(" public static readonly __pulumiType = '%s';", res.info.Tok)
w.Writefmtln("")
w.Writefmtln(" /**")
w.Writefmtln(" * Returns true if the given object is an instance of %s. This is designed to work even", name)
w.Writefmtln(" * when multiple copies of the Pulumi SDK have been loaded into the same process.")
w.Writefmtln(" */")
w.Writefmtln(" public static isInstance(obj: any): obj is %s {", name)
w.Writefmtln(" if (obj === undefined || obj === null) {")
w.Writefmtln(" return false;")
w.Writefmtln(" }")
w.Writefmtln(" return obj['__pulumiType'] === %s.__pulumiType;", name)
w.Writefmtln(" }")
w.Writefmtln("")

// Emit all properties (using their output types).
// TODO[pulumi/pulumi#397]: represent sensitive types using a Secret<T> type.
ins := make(map[string]bool)
Expand Down Expand Up @@ -591,7 +606,7 @@ func (g *nodeJSGenerator) emitResourceType(mod *module, res *resourceType) (stri
// w.Writefmtln(" }")

// Now invoke the super constructor with the type, name, and a property map.
w.Writefmtln(` super("%s", name, inputs, opts);`, res.info.Tok)
w.Writefmtln(` super(%s.__pulumiType, name, inputs, opts);`, name)

// Finish the class.
w.Writefmtln(" }")
Expand Down

0 comments on commit 7ace3e9

Please sign in to comment.