67 lines
1.5 KiB
JavaScript
67 lines
1.5 KiB
JavaScript
// import knex from './knex';
|
|
import { verifyPrivilege } from './privileges';
|
|
import knex from './knex';
|
|
import { HttpError } from './errors';
|
|
|
|
import { fetchShelf, curateDatabaseShelf } from './shelves';
|
|
import { curateDatabaseUser } from './users';
|
|
|
|
function curatePost(post) {
|
|
const curatedPost = {
|
|
id: post.id,
|
|
title: post.title,
|
|
body: post.body,
|
|
url: post.url,
|
|
shelfId: post.shelf_id,
|
|
createdAt: post.created_at,
|
|
shelf: curateDatabaseShelf(post.shelf),
|
|
user: curateDatabaseUser(post.user),
|
|
};
|
|
|
|
return curatedPost;
|
|
}
|
|
|
|
async function fetchShelfPosts(shelfId, limit = 100) {
|
|
const shelf = await fetchShelf(shelfId);
|
|
|
|
const posts = await knex('posts')
|
|
.select('posts.*', knex.raw('row_to_json(users) as user'), knex.raw('row_to_json(shelves) as shelf'))
|
|
.leftJoin('users', 'users.id', 'posts.user_id')
|
|
.leftJoin('shelves', 'shelves.id', 'posts.shelf_id')
|
|
.where('shelf_id', shelf.id)
|
|
.orderBy('created_at', 'desc')
|
|
.limit(limit);
|
|
|
|
return posts.map((post) => curatePost(post));
|
|
}
|
|
|
|
async function createPost(post, shelfId, user) {
|
|
await verifyPrivilege('createPost', user);
|
|
|
|
const shelf = await fetchShelf(shelfId);
|
|
|
|
if (!shelf) {
|
|
throw new HttpError({
|
|
statusMessage: 'The target shelf does not exist',
|
|
statusCode: 404,
|
|
});
|
|
}
|
|
|
|
const postId = await knex('posts')
|
|
.insert({
|
|
title: post.title,
|
|
body: post.body,
|
|
url: post.url,
|
|
shelf_id: shelf.id,
|
|
user_id: user.id,
|
|
})
|
|
.returning('id');
|
|
|
|
return postId;
|
|
}
|
|
|
|
export {
|
|
createPost,
|
|
fetchShelfPosts,
|
|
};
|