Walkthrough: using Typescript and imports for pb_hooks #291
benallfree
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I spent the day trying some different solutions to using pb_hooks in https://pockethost.io. We have some server-side functions that in theory could be moved to hooks, but I found it difficult to manage package dependencies and I really wanted full Typescript support too.
Here's what I came up with. Let me know what you guys think!
Folder structure
Create
./src/hooks/*.pb.ts
files. These are your entry points. I recommend making many of them and keeping them focused on specific tasks. While you could make oneonRecordAfterUpdateRequest
to hold the ocean, it's better to use many purpose-builtonRecordAfterUpdateRequest
handlers. So make one per.pb.ts
file.Example:
Build step
In
package.json
:During development, run
yarn dev:hooks
to watch for changes tosrc/hooks
and compile them intopb_hooks
.Running PocketBase with your generated hooks
Including libraries, modules, etc.
Add
./src/hooks/lib.ts
. This file will serve as the 'kitchen sink' library entry point. You can include all your goodies in it just like you always do. Keep in mind, you'll need torequire()
this in your hook files, so be aware of how large this library grows. It will build as./pb_hooks/lib.js
which is not autoloaded by PocketBase.Some Typescript kung fu makes this work by creating a type that is the entire interface to your library:
Using that, you can then require your library and cast it to the
Lib
type. This works in VSCode, too, even though there is no.js
file!Putting it all together:
To use it in a hook, do this:
Special note about assertion functions
If you use Typescript assertion functions, you need to know that they require an explicit type annotation.
Suppose you have
In
lib.ts
, you'll want to doAnd in your hook files (
*.pb.ts
), it'll look like thisBeta Was this translation helpful? Give feedback.
All reactions