Skip to content

Instantly share code, notes, and snippets.

@umutyerebakmaz
Last active October 16, 2019 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umutyerebakmaz/fa38701dc2405264146f9a842e841ec9 to your computer and use it in GitHub Desktop.
Save umutyerebakmaz/fa38701dc2405264146f9a842e841ec9 to your computer and use it in GitHub Desktop.
its my server file.
import 'reflect-metadata';
import { MongoClient } from 'mongodb';
import { AccountsServer } from '@accounts/server';
import { AccountsPassword } from '@accounts/password';
import AccountsMongoDB from '@accounts/mongo';
import { ApolloServer, attachDirectiveResolvers } from 'apollo-server';
import { AppModule } from '@modules/app/app.module';
import * as dotenv from "dotenv";
dotenv.config();
import nodemailer from 'nodemailer';
import express from "express";
// mongodb setup
const PORT = process.env['PORT'];
const MONGO_URI = process.env['MONGO_URI'];
const TOKEN_SECRET = process.env['TOKEN_SECRET'];
// express setup
const app = express();
const port = 3000; // default port to listen
// start the express server
app.listen( port, () => {
console.log( `express server: http://localhost:${ port }` );
} );
// main app server
async function main() {
console.time('Bootstrap');
const mongoClient = await MongoClient.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoClient.db();
// initiate modemailer
const transporter = nodemailer.createTransport(
{
host: "smtp.mailtrap.io",
port: 2525,
auth: {
user: "92d3b9a80c843a",
pass: "f25e19d658830f"
}
}
);
// Options for AccountsServer
const options = {
sendMail: async ({ from, subject, to, text, html }) => {
await transporter.sendMail({
from,
to,
subject,
text,
html,
});
},
};
// AccountsServer
const accountsServer = new AccountsServer(
{
db: new AccountsMongoDB(db),
tokenSecret: TOKEN_SECRET,
sendMail: options.sendMail
},
{
password: new AccountsPassword({
// This option is called when a new user create an account
// Inside we can apply our logic to validate the user fields
validateNewUser: user => {
if (user.profile.fullname.length < 2) {
throw new Error('Ad Soyad çok kısa');
}
return user;
},
}),
}
);
const { schema } = AppModule.forRoot({
accountsServer,
db
});
attachDirectiveResolvers(schema, {
id: (_, { _id }) => _id.toString(),
});
const apolloServer = new ApolloServer({
schema,
playground: true,
introspection: true,
context: session => session,
});
const { url } = await apolloServer.listen(PORT);
console.info(`apollo server: ${url}`);
console.timeEnd('Bootstrap');
}
main().catch(console.error);
extend type Query {
allUsers: [User]
userById(id: ID!): User
userByUsername(username: String!): User
usersWithPaginate(username: String, fullname: String, skip: Int, limit: Int): [User]
usersCount: Int
me: User
}
import { QueryResolvers } from "@models";
import { UsersProvider } from "../providers/users.provider";
export const Query: QueryResolvers = {
allUsers: (root, args, { injector }) => injector.get(UsersProvider).getAllUsers(),
userByUsername: (_, { username }, { injector }) => injector.get(UsersProvider).getUserByUsername(username)
}
enum AccountType {
Admin
Editor
Member
}
extend type User @entity {
id: ID @id
accountType: AccountType
profile: Profile
}
extend input CreateUserInput {
accountType: String = "Member"
profile: CreateUserProfileInput!
}
type Profile {
fullname: String
dateOfBirth: String
placeOfBirth: String
gender: String
job: String
web: String
bio: String
}
input CreateUserProfileInput {
fullname: String!
dateOfBirth: String!
placeOfBirth: String
gender: String!
job: String
web: String
bio: String
}
import { Injectable } from "@graphql-modules/di";
import { Db, Collection, ObjectID } from "mongodb";
import { UserDbObject, CreateUserInput } from '@models';
@Injectable()
export class UsersProvider {
collection: Collection<UserDbObject>;
constructor(db: Db) {
this.collection = db.collection('users');
}
getAllUsers() {
return this.collection.find().toArray();
}
getUserById(id: string) {
return this.collection.findOne({ _id: new ObjectID(id) });
}
getUserByUsername(username: string) {
return this.collection.findOne({ username: username });
}
getUsersCount() {
return this.collection.countDocuments();
}
me(id: string) {
return this.collection.findOne({ _id: new ObjectID(id) });
}
async updateUser(id: string, user: CreateUserInput): Promise<UserDbObject> {
const _id = new ObjectID(id);
await this.collection.updateOne({ _id }, { $set: user });
return {
_id,
...user
} as UserDbObject;
}
async deleteUser(id: string, user: CreateUserInput): Promise<UserDbObject> {
const _id = new ObjectID(id);
await this.collection.deleteOne({ _id });
return {
_id,
...user
} as UserDbObject;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment