Skip to content
This repository has been archived by the owner on Oct 1, 2019. It is now read-only.

Commit

Permalink
[#790] Add createUserPost and updateUserPost controllers
Browse files Browse the repository at this point in the history
  • Loading branch information
voidxnull committed Feb 14, 2017
1 parent 19a1153 commit a637253
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
64 changes: 64 additions & 0 deletions src/api/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3342,8 +3342,72 @@ export default class ApiController {
ctx.body = messages;
}

createUserPost = async (ctx) => {
if (!ctx.session || !ctx.session.user) {
ctx.status = 403;
ctx.body = { error: 'You are not authorized' };
return;
}

const UserPost = this.bookshelf.model('UserPost');

const post = new UserPost(_.pick(ctx.request.body, ['text', 'type', 'more']));

try {
await post.save();
ctx.body = await post.fetch();
} catch (e) {
this.processError(ctx, e);
}
}

updateUserPost = async (ctx) => {
if (!ctx.session || !ctx.session.user) {
ctx.status = 403;
ctx.body = { error: 'You are not authorized' };
return;
}

const UserPost = this.bookshelf.model('UserPost');

const post = new UserPost({ id: ctx.params.id, user_id: ctx.session.user });

try {
await post.save(_.pick(ctx.request.body, ['text', 'type', 'more']), { patch: true });
ctx.body = await post.fetch();
} catch (e) {
this.processError(ctx, e);
}
}

// ========== Helpers ==========

/**
* Sets the response body in case of error
* ```
* {
* errors: { fieldName: ['Some message']] }, // Only if e is a Checkit.Error
* error: 'Human readable message'
* }
* ```
* @param ctx Koa context
* @param {Error} e
*/
processError(ctx, e) {
ctx.status = 500;

if (e instanceof Checkit.Error) {
ctx.body = {
...e.toJSON(),
error: e.toString()
};
} else {
ctx.body = {
error: e.message
};
}
}

async areMutuallyFollowed(user1Id, user2Id) {
const knex = this.bookshelf.knex;

Expand Down
3 changes: 3 additions & 0 deletions src/api/routing.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@ export function initApi(bookshelf, sphinx) {
api.post('/user/:username/unfollow', controller.unfollowUser);
api.post('/user/:username/ignore', controller.ignoreUser);

api.post('/user-posts', controller.createUserPost);
api.post('/user-posts/:id', controller.updateUserPost);

api.get('/user/verify/:hash', controller.verifyEmail);
api.post('/user/', controller.updateUser);
api.post('/user/password', controller.changePassword);
Expand Down

0 comments on commit a637253

Please sign in to comment.