zenstack 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2022 ZenStack Language Tools
3
+ Copyright (c) 2022 ZenStack
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md ADDED
@@ -0,0 +1,281 @@
1
+ <div align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://user-images.githubusercontent.com/104139426/197796502-1bcb8052-a7b1-42de-bfc8-a14e045ac1c3.png">
4
+ <img src="https://user-images.githubusercontent.com/104139426/197796006-52d8d334-413b-4eda-8094-4024c0eaf9b3.png" height="128">
5
+ </picture>
6
+ <h1>ZenStack</h1>
7
+ <a href="https://www.npmjs.com/package/zenstack">
8
+ <img src="https://img.shields.io/npm/v/zenstack">
9
+ </a>
10
+ <a href="https://twitter.com/intent/tweet?text=Wow%20%40zenstackhq">
11
+ <img src="https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fzenstackhq%2Fzenstack">
12
+ </a>
13
+ <a href="https://discord.gg/6HhebQynfz">
14
+ <img src="https://img.shields.io/discord/1035538056146595961">
15
+ </a>
16
+ <a href="https://github.com/zenstackhq/zenstack/blob/dev/LICENSE">
17
+ <img src="https://img.shields.io/badge/license-MIT-green">
18
+ </a>
19
+ </div>
20
+
21
+ ## What is ZenStack?
22
+
23
+ ZenStack is a toolkit for simplifying full-stack development with Node.js web frameworks like [Next.js](https://nextjs.org/), [Nuxt.js](https://nuxtjs.org/) <img src="https://img.shields.io/badge/-Coming%20Soon-lightgray" height="12" align="top">, and [SvelteKit](https://kit.svelte.dev/) <img src="https://img.shields.io/badge/-Coming%20Soon-lightgray" height="12" align="top">, using Typescript language.
24
+
25
+ Thanks to the increasing power of frameworks, building a complex web app within one unified framework is becoming more practical than ever. However, you'll still need to spend a significant amount of energy designing and building up your app's server-side part.
26
+
27
+ Things that make you stressed include:
28
+
29
+ - What kind of API to use? RESTful or GraphQL?
30
+ - How to model your data and map the model to both source code and database (ORM)?
31
+ - How to implement CRUD operations? Manually construct it or use a generator?
32
+ - How to evolve your data model?
33
+ - How to authenticate users and authorize their requests?
34
+
35
+ ZenStack aims to simplify these tasks by providing:
36
+
37
+ - An intuitive data modeling language for defining data types, relations, and access policies
38
+
39
+ ```prisma
40
+ model User {
41
+ id String @id @default(cuid())
42
+ email String @unique
43
+
44
+ // one-to-many relation to Post
45
+ posts Post[]
46
+ }
47
+
48
+ model Post {
49
+ id String @id @default(cuid())
50
+ title String
51
+ content String
52
+ published Boolean @default(false)
53
+
54
+ // one-to-many relation from User
55
+ author User? @relation(fields: [authorId], references: [id])
56
+ authorId String?
57
+
58
+ // must signin to CRUD any post
59
+ @@deny('all', auth() == null)
60
+
61
+ // allow CRUD by author
62
+ @@allow('all', author == auth())
63
+ }
64
+ ```
65
+
66
+ - Auto-generated CRUD services and strongly typed front-end library
67
+
68
+ ```jsx
69
+ // React example
70
+
71
+ const { find } = usePost();
72
+ const posts = get({ where: { public: true } });
73
+ // only posts owned by current login user are returned
74
+ return (
75
+ <>
76
+ {posts?.map((post) => (
77
+ <Post key={post.id} post={post} />
78
+ ))}
79
+ </>
80
+ );
81
+ ```
82
+
83
+ Since CRUD APIs are automatically generated with access policies injected, you can safely implement most of your business logic in your front-end code. Read operations never return data that's not supposed to be visible to the current user, and writes will be rejected if unauthorized. The generated front-end library also supports nested writes, allowing you to make a batch of creates/updates atomically, eliminating the need for explicitly using a transaction.
84
+
85
+ ZenStack is heavily inspired and built over [Prisma](https://www.prisma.io) ORM, which is, in our opinion, the best ORM toolkit in the market. Familiarity with Prisma should make it easy to pick up ZenStack, but it's not a prerequisite since the modeling language is intuitive and the development workflow is straightforward.
86
+
87
+ ## Getting started
88
+
89
+ ### [For Next.js](docs/get-started/next-js.md)
90
+
91
+ ### For Nuxt.js <img src="https://img.shields.io/badge/-Coming%20Soon-lightgray" height="12" align="top">
92
+
93
+ ### For SvelteKit <img src="https://img.shields.io/badge/-Coming%20Soon-lightgray" height="12" align="top">
94
+
95
+ ## How does it work?
96
+
97
+ ZenStack has four essential responsibilities:
98
+
99
+ 1. Modeling data and mapping the model to DB schema and program types
100
+ 1. Integrating with authentication
101
+ 1. Generating CRUD APIs and enforcing data access policies
102
+ 1. Providing type-safe client CRUD library
103
+
104
+ Let's briefly go through each of them in this section.
105
+
106
+ ### Data modeling
107
+
108
+ ZenStack uses a schema language called `ZModel` to define data types and their relations. The `zenstack` CLI takes a schema file as input and generates database client code. Such client code allows you to program against database in server-side code in a fully typed way without writing any SQL. It also provides commands for synchronizing data models with DB schema, and generating "migration records" when your data model evolves.
109
+
110
+ Internally, ZenStack entirely relies on Prisma for ORM tasks. The ZModel language is a superset of Prisma's schema language. When `zenstack generate` is run, a Prisma schema named 'schema.prisma' is generated beside your ZModel file. You don't need to commit schema.prisma to source control. The recommended practice is to run `zenstack generate` during deployment, so Prisma schema is regenerated on the fly.
111
+
112
+ ### Authentication
113
+
114
+ ZenStack is not an authentication library, but it gets involved in two ways.
115
+
116
+ Firstly, if you use any authentication method that involves persisting users' identity, you'll model the user's shape in ZModel. Some auth libraries, like [NextAuth](https://next-auth.js.org/), require user entity to include specific fields, and your model should fulfill such requirements. In addition, credential-based authentication requires validating user-provided credentials, and you should implement this using the database client generated by ZenStack.
117
+
118
+ To simplify the task, ZenStack automatically generates an adapter for NextAuth when it detects that the `next-auth` npm package is installed. Please refer to [the starter code](https://github.com/zenstackhq/nextjs-auth-starter/blob/main/pages/api/auth/%5B...nextauth%5D.ts) for how to use it. We'll keep adding integrations/samples for other auth libraries in the future.
119
+
120
+ Secondly, authentication is almost always connected to authorization. ZModel allows you to reference the current login user via `auth()` function in access policy expressions. Like,
121
+
122
+ ```prisma
123
+ model Post {
124
+ author User @relation(fields: [authorId], references: [id])
125
+ ...
126
+
127
+ @@deny('all', auth() == null)
128
+ @@allow('all', auth() == author)
129
+ ```
130
+
131
+ The value returned by `auth()` is provided by your auth solution via the `getServerUser` hook function you provide when mounting ZenStack APIs. Check [this code](https://github.com/zenstackhq/nextjs-auth-starter/blob/main/pages/api/zenstack/%5B...path%5D.ts) for an example.
132
+
133
+ ### Data access policy
134
+
135
+ The primary value that ZenStack adds over a traditional ORM is the built-in data access policy engine. This allows most business logic to be safely implemented in front-end code. Since ZenStack delegates database access to Prisma, it enforces access policies by analyzing queries sent to Prisma and injecting guarding conditions. For example, suppose we have a policy saying "a post can only be accessed by its author if it's not published", expressed in ZModel as:
136
+
137
+ ```prisma
138
+ @@deny('all', auth() != author && !published)
139
+ ```
140
+
141
+ When client code sends a query to list all `Post`s, ZenStack's generated code intercepts it and injects the `where` clause before passing it through to Prisma (conceptually):
142
+
143
+ ```js
144
+ {
145
+ where: {
146
+ AND: [
147
+ { ...userProvidedFilter },
148
+ {
149
+ // injected by ZenStack, "user" object is fetched from context
150
+ NOT: {
151
+ AND: [
152
+ { author: { not: { id: user.id } } },
153
+ { published: { not: true } },
154
+ ],
155
+ },
156
+ },
157
+ ];
158
+ }
159
+ }
160
+ ```
161
+
162
+ Similar procedures are applied to write operations and more complex queries involving nested reads and writes. To ensure good performance, ZenStack generates conditions statically, so it doesn't need to introspect ZModel at runtime. The engine also makes the best effort to push down policy constraints to the database to avoid fetching data unnecessarily and discarding afterward.
163
+
164
+ Please **beware** that policy checking is only applied when data access is done using the generated client-side hooks or, equivalently, the RESTful API. If you use `service.db` to access the database directly from server-side code, policies are bypassed, and you have to do all necessary checking by yourself. We've planned to add helper functions for "injecting" the policy checking on the server side in the future.
165
+
166
+ ### Type-safe client library
167
+
168
+ Thanks to Prisma's power, ZenStack generates accurate Typescript types for your data models:
169
+
170
+ - The model itself
171
+ - Argument types for listing models, including filtering, sorting, pagination, and nested reads for related models
172
+ - Argument types for creating and updating models, including nested writes for related models
173
+
174
+ The cool thing is that the generated types are shared between client-side and server-side code, so no matter which side of code you're writing, you can always enjoy the pleasant IDE intellisense and typescript compiler's error checking.
175
+
176
+ ## Programming with the generated code
177
+
178
+ ### Client-side
179
+
180
+ #### For Next.js
181
+
182
+ The generated CRUD services should be mounted at `/api/zenstack` route. React hooks are generated for calling these services without explicitly writing Http requests.
183
+
184
+ The following hooks methods are generated:
185
+
186
+ - find: listing entities with filtering, ordering, pagination, and nested relations
187
+
188
+ ```ts
189
+ const { find } = usePost();
190
+ // lists unpublished posts with their author's data
191
+ const posts = find({
192
+ where: { published: false },
193
+ include: { author: true },
194
+ orderBy: { updatedAt: 'desc' },
195
+ });
196
+ ```
197
+
198
+ - get: fetching a single entity by id, with nested relations
199
+
200
+ ```ts
201
+ const { get } = usePost();
202
+ // fetches a post with its author's data
203
+ const post = get(id, {
204
+ include: { author: true },
205
+ });
206
+ ```
207
+
208
+ - create: creating a new entity, with the support for nested creation of related models
209
+
210
+ ```ts
211
+ const { create } = usePost();
212
+ // creating a new post for current user with a nested comment
213
+ const post = await create({
214
+ data: {
215
+ title: 'My New Post',
216
+ author: {
217
+ connect: { id: session.user.id },
218
+ },
219
+ comments: {
220
+ create: [{ content: 'First comment' }],
221
+ },
222
+ },
223
+ });
224
+ ```
225
+
226
+ - update: updating an entity, with the support for nested creation/update of related models
227
+
228
+ ```ts
229
+ const { update } = usePost();
230
+ // updating a post's content and create a new comment
231
+ const post = await update(id, {
232
+ data: {
233
+ const: 'My post content',
234
+ comments: {
235
+ create: [{ content: 'A new comment' }],
236
+ },
237
+ },
238
+ });
239
+ ```
240
+
241
+ - del: deleting an entity
242
+
243
+ ```js
244
+ const { del } = usePost();
245
+ const post = await del(id);
246
+ ```
247
+
248
+ Internally ZenStack generated code uses [SWR](https://swr.vercel.app/) to do data fetching so that you can enjoy its caching, polling, and automatic revalidation features.
249
+
250
+ ### Server-side
251
+
252
+ If you need to do server-side coding, either through implementing an API endpoint or by using `getServerSideProps` for SSR, you can directly access the database client generated by Prisma:
253
+
254
+ ```ts
255
+ import service from '@zenstackhq/runtime';
256
+
257
+ export const getServerSideProps: GetServerSideProps = async () => {
258
+ const posts = await service.db.post.findMany({
259
+ where: { published: true },
260
+ include: { author: true },
261
+ });
262
+ return {
263
+ props: { posts },
264
+ };
265
+ };
266
+ ```
267
+
268
+ **Please note** that server-side database access is not protected by access policies. This is by-design so as to provide a way of bypassing the policies. Please make sure you implement authorization properly.
269
+
270
+ ## What's next?
271
+
272
+ ### [Learning the ZModel language](/docs/get-started/learning-the-zmodel-language.md)
273
+
274
+ ### [Evolving data model with migration](/docs/ref/evolving-data-model-with-migration.md)
275
+
276
+ ### [Database hosting considerations](/docs/ref/database-hosting-considerations.md)
277
+
278
+ ## Reach out to us for issues, feedback and ideas!
279
+
280
+ [Discord](https://discord.gg/dbuC9ZWc) [Twitter](https://twitter.com/zenstackhq)
281
+ [Discussions](../discussions) [Issues](../issues)