mongodb-crud

This commit is contained in:
King Wang
2021-06-26 23:41:37 +08:00
parent aa5da74b6a
commit 4a74c31258
36 changed files with 1212 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
import { ApiCall } from "tsrpc";
import { Global } from "../models/Global";
import { ReqAddPost, ResAddPost } from "../shared/protocols/PtlAddPost";
export async function ApiAddPost(call: ApiCall<ReqAddPost, ResAddPost>) {
console.log('cccgasdgasd', call.service.conf)
if (call.service.conf) {
// if (没登录) {
// call.error('你还没登录');
// return;
// }
}
let op = await Global.collection('Post').insertOne({
...call.req.newPost,
create: {
uid: 'xxx',
time: new Date()
},
visitedNum: 0
});
call.succ({
insertedId: op.insertedId.toHexString()
})
}

View File

@@ -0,0 +1,12 @@
import { ObjectID } from 'mongodb';
import { ApiCall } from "tsrpc";
import { Global } from "../models/Global";
import { ReqDelPost, ResDelPost } from "../shared/protocols/PtlDelPost";
export async function ApiDelPost(call: ApiCall<ReqDelPost, ResDelPost>) {
let op = await Global.collection('Post').deleteOne({
_id: new ObjectID(call.req._id)
})
call.succ({});
}

View File

@@ -0,0 +1,22 @@
import { ObjectID } from 'mongodb';
import { ApiCall } from "tsrpc";
import { Global } from "../models/Global";
import { ReqGetPost, ResGetPost } from "../shared/protocols/PtlGetPost";
export async function ApiGetPost(call: ApiCall<ReqGetPost, ResGetPost>) {
let op = await Global.collection('Post').findOne({
_id: new ObjectID(call.req._id)
});
if (!op) {
call.error('Post 不存在');
return;
}
call.succ({
post: {
...op,
_id: op._id.toHexString()
}
})
}

View File

@@ -0,0 +1,22 @@
import { ObjectID } from 'mongodb';
import { ApiCall } from "tsrpc";
import { Global } from "../models/Global";
import { ReqUpdatePost, ResUpdatePost } from "../shared/protocols/PtlUpdatePost";
export async function ApiUpdatePost(call: ApiCall<ReqUpdatePost, ResUpdatePost>) {
let { _id, ...update } = call.req.update;
let op = await Global.collection('Post').updateOne({
_id: new ObjectID(_id)
}, {
$set: update
});
console.log('ssss', {
matchedCount: op.matchedCount
})
call.succ({
matchedCount: op.matchedCount
})
}

View File

@@ -0,0 +1,26 @@
import * as path from "path";
import { HttpServer } from "tsrpc";
import { Global } from "./models/Global";
import { serviceProto } from "./shared/protocols/serviceProto";
// Create the Server
const server = new HttpServer(serviceProto, {
port: 3000,
cors: '*'
});
// Entry function
async function main() {
// Auto implement APIs
await server.autoImplementApi(path.resolve(__dirname, 'api'));
await Global.init(server.logger);
await server.start();
};
main().catch(e => {
// Exit if any error during the startup
server.logger.error(e);
process.exit(-1);
});

View File

@@ -0,0 +1,4 @@
export const BackConfig = {
// Please replace by your db
mongoDb: 'mongodb://username:password@xxx.com:27017/test?authSource=admin',
}

View File

@@ -0,0 +1,40 @@
import { Collection, Db, MongoClient } from "mongodb";
import { Logger } from "tsrpc";
import { BackConfig } from "./BackConfig";
import { DbPost } from "./dbItems/DbPost";
export class Global {
static db: Db;
static async init(logger?: Logger) {
this.db = await this._getMongoDb(BackConfig.mongoDb, logger);
}
private static _getMongoDb(uri: string, logger?: Logger): Promise<Db> {
logger?.log(`Start connecting db...(${uri})`)
let promise = new Promise<Db>((rs, rj) => {
MongoClient.connect(uri, {
useUnifiedTopology: true,
}, (err, client) => {
if (err) {
logger?.error('× Failed connected db.', err)
rj(err);
} else {
logger?.log(`√ Connect db succ. (${uri})`)
rs(client.db());
}
})
})
return promise;
}
static collection<T extends keyof DbCollectionType>(col: T): Collection<DbCollectionType[T]> {
return this.db.collection(col);
}
}
export interface DbCollectionType {
Post: DbPost
}

View File

@@ -0,0 +1,7 @@
import { ObjectID } from "bson";
import { Overwrite } from "tsrpc";
import { Post } from "../../shared/protocols/models/Post";
export type DbPost = Overwrite<Post, {
_id: ObjectID
}>

View File

@@ -0,0 +1,9 @@
import { Post } from "./models/Post";
export interface ReqAddPost {
newPost: Omit<Post, '_id' | 'create' | 'update' | 'visitedNum'>;
}
export interface ResAddPost {
insertedId: string;
}

View File

@@ -0,0 +1,7 @@
export interface ReqDelPost {
_id: string;
}
export interface ResDelPost {
}

View File

@@ -0,0 +1,9 @@
import { Post } from "./models/Post";
export interface ReqGetPost {
_id: string;
}
export interface ResGetPost {
post: Post;
}

View File

@@ -0,0 +1,9 @@
import { Post } from "./models/Post";
export interface ReqUpdatePost {
update: { _id: string } & Partial<Pick<Post, 'title' | 'content'>>;
}
export interface ResUpdatePost {
matchedCount: number;
}

View File

@@ -0,0 +1,17 @@
export interface Post {
_id: string;
author: string;
title: string;
content: string;
visitedNum: number;
create: {
uid: string;
time: Date;
}
update?: {
uid: string,
time: Date
}
}

View File

@@ -0,0 +1,276 @@
import { ServiceProto } from 'tsrpc-proto';
import { ReqAddPost, ResAddPost } from './PtlAddPost';
import { ReqDelPost, ResDelPost } from './PtlDelPost';
import { ReqGetPost, ResGetPost } from './PtlGetPost';
import { ReqUpdatePost, ResUpdatePost } from './PtlUpdatePost';
export interface ServiceType {
api: {
"AddPost": {
req: ReqAddPost,
res: ResAddPost
},
"DelPost": {
req: ReqDelPost,
res: ResDelPost
},
"GetPost": {
req: ReqGetPost,
res: ResGetPost
},
"UpdatePost": {
req: ReqUpdatePost,
res: ResUpdatePost
}
},
msg: {
}
}
export const serviceProto: ServiceProto<ServiceType> = {
"version": 16,
"services": [
{
"id": 0,
"name": "AddPost",
"type": "api"
},
{
"id": 1,
"name": "DelPost",
"type": "api"
},
{
"id": 2,
"name": "GetPost",
"type": "api"
},
{
"id": 3,
"name": "UpdatePost",
"type": "api"
}
],
"types": {
"PtlAddPost/ReqAddPost": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "newPost",
"type": {
"target": {
"type": "Reference",
"target": "models/Post/Post"
},
"keys": [
"_id",
"create",
"update",
"visitedNum"
],
"type": "Omit"
}
}
]
},
"models/Post/Post": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "_id",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "author",
"type": {
"type": "String"
}
},
{
"id": 2,
"name": "title",
"type": {
"type": "String"
}
},
{
"id": 3,
"name": "content",
"type": {
"type": "String"
}
},
{
"id": 4,
"name": "visitedNum",
"type": {
"type": "Number"
}
},
{
"id": 5,
"name": "create",
"type": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "uid",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "time",
"type": {
"type": "Date"
}
}
]
}
},
{
"id": 6,
"name": "update",
"type": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "uid",
"type": {
"type": "String"
}
},
{
"id": 1,
"name": "time",
"type": {
"type": "Date"
}
}
]
},
"optional": true
}
]
},
"PtlAddPost/ResAddPost": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "insertedId",
"type": {
"type": "String"
}
}
]
},
"PtlDelPost/ReqDelPost": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "_id",
"type": {
"type": "String"
}
}
]
},
"PtlDelPost/ResDelPost": {
"type": "Interface"
},
"PtlGetPost/ReqGetPost": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "_id",
"type": {
"type": "String"
}
}
]
},
"PtlGetPost/ResGetPost": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "post",
"type": {
"type": "Reference",
"target": "models/Post/Post"
}
}
]
},
"PtlUpdatePost/ReqUpdatePost": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "update",
"type": {
"type": "Intersection",
"members": [
{
"id": 1,
"type": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "_id",
"type": {
"type": "String"
}
}
]
}
},
{
"id": 3,
"type": {
"type": "Partial",
"target": {
"target": {
"type": "Reference",
"target": "models/Post/Post"
},
"keys": [
"title",
"content"
],
"type": "Pick"
}
}
}
]
}
}
]
},
"PtlUpdatePost/ResUpdatePost": {
"type": "Interface",
"properties": [
{
"id": 0,
"name": "matchedCount",
"type": {
"type": "Number"
}
}
]
}
}
};