Last active
February 9, 2016 20:18
-
-
Save Jabher/02e9c701168e8376f7f7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class User extends Record { | |
| posts = new Relation(this, 'wrote'); | |
| //yes. we're passing object and it will be dumped into DB without a schema | |
| async createPost(postParams) { | |
| const tx = this.connection.transaction() | |
| const post = await new Post(postParams) | |
| .save(tx) | |
| await this.posts.add(post, tx) | |
| //or we can write this as Relation#only is async getter/setter method | |
| await post.user(this, tx) | |
| await tx.commit() | |
| return post | |
| } | |
| } | |
| class Post extends Record { | |
| user = ::new Relation(this, 'wrote', {target: User, direction: -1}).only; | |
| //or if you do not like bind functions from stage-0 | |
| constructor(...args) { | |
| super(...args) | |
| //target option is optional and limits resulting entries to exact class | |
| //direction shows, emm, direction of relation. 1 by default, -1 is reverse, 0 is any-direction relation | |
| const users = new Relation(this, 'wrote', {target: User, direction: -1}) | |
| this.user = users.only.bind(user) | |
| } | |
| } | |
| // let's imagine it's some hybrid of koa and express app. It will not work, but it's extremely readable. | |
| app | |
| .use(async(ctx, next) => | |
| ctx.user = ctx.session && ctx.session.uuid ? await User.byUuid(ctx.session.uuid) : null) | |
| .get('/posts', async(ctx) => | |
| ctx.body = await Post.where({}, {limit: ctx.query.limit, offset: ctx.query.offset})) | |
| .get('/posts/own', async(ctx) => | |
| ctx.body = await ctx.user.posts.entries()) | |
| .get('/posts/:id', async(ctx) => { | |
| const post = await Post.byUuid(ctx.query.id) | |
| ctx.body = {...post, user: await post.user()} | |
| }) | |
| .post('/posts', async(ctx) => { | |
| if (!ctx.user) | |
| return ctx.status = 403 | |
| if (!req.params.body || !req.params.title) | |
| return ctx.status = 400 | |
| const post = await ctx.user.createPost(req.params) | |
| res.redirect(`/posts/${post.uuid}`) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment