wip
This commit is contained in:
29
src/api/endpoints/bbs/threads/create.ts
Normal file
29
src/api/endpoints/bbs/threads/create.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Module dependencies
|
||||
*/
|
||||
import $ from 'cafy';
|
||||
import Thread from '../../../models/bbs-thread';
|
||||
import serialize from '../../../serializers/bbs-thread';
|
||||
|
||||
/**
|
||||
* Create a thread
|
||||
*
|
||||
* @param {any} params
|
||||
* @param {any} user
|
||||
* @return {Promise<any>}
|
||||
*/
|
||||
module.exports = async (params, user) => new Promise(async (res, rej) => {
|
||||
// Get 'title' parameter
|
||||
const [title, titleErr] = $(params.title).string().range(1, 100).$;
|
||||
if (titleErr) return rej('invalid title param');
|
||||
|
||||
// Create a thread
|
||||
const thread = await Thread.insert({
|
||||
created_at: new Date(),
|
||||
user_id: user._id,
|
||||
title: title
|
||||
});
|
||||
|
||||
// Response
|
||||
res(await serialize(thread));
|
||||
});
|
13
src/api/models/bbs-thread.ts
Normal file
13
src/api/models/bbs-thread.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import * as mongo from 'mongodb';
|
||||
import db from '../../db/mongodb';
|
||||
|
||||
const collection = db.get('bbs_threads');
|
||||
|
||||
export default collection as any; // fuck type definition
|
||||
|
||||
export type IBbsThread = {
|
||||
_id: mongo.ObjectID;
|
||||
created_at: Date;
|
||||
title: string;
|
||||
user_id: mongo.ObjectID;
|
||||
};
|
44
src/api/serializers/bbs-thread.ts
Normal file
44
src/api/serializers/bbs-thread.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Module dependencies
|
||||
*/
|
||||
import * as mongo from 'mongodb';
|
||||
import deepcopy = require('deepcopy');
|
||||
import { IUser } from '../models/user';
|
||||
import { default as Thread, IBbsThread } from '../models/bbs-thread';
|
||||
|
||||
/**
|
||||
* Serialize a thread
|
||||
*
|
||||
* @param thread target
|
||||
* @param me? serializee
|
||||
* @return response
|
||||
*/
|
||||
export default (
|
||||
thread: string | mongo.ObjectID | IBbsThread,
|
||||
me?: string | mongo.ObjectID | IUser
|
||||
) => new Promise<any>(async (resolve, reject) => {
|
||||
|
||||
let _thread: any;
|
||||
|
||||
// Populate the thread if 'thread' is ID
|
||||
if (mongo.ObjectID.prototype.isPrototypeOf(thread)) {
|
||||
_thread = await Thread.findOne({
|
||||
_id: thread
|
||||
});
|
||||
} else if (typeof thread === 'string') {
|
||||
_thread = await Thread.findOne({
|
||||
_id: new mongo.ObjectID(thread)
|
||||
});
|
||||
} else {
|
||||
_thread = deepcopy(thread);
|
||||
}
|
||||
|
||||
// Rename _id to id
|
||||
_thread.id = _thread._id;
|
||||
delete _thread._id;
|
||||
|
||||
// Remove needless properties
|
||||
delete _thread.user_id;
|
||||
|
||||
resolve(_thread);
|
||||
});
|
Reference in New Issue
Block a user