repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
plumier/examples
|
02-controller/query-parser-typeorm/src/controller/users-controller.ts
|
<filename>02-controller/query-parser-typeorm/src/controller/users-controller.ts
import { Entity, Column, PrimaryGeneratedColumn, getRepository } from "typeorm"
import { filterParser, meta, orderParser, route, selectParser, SelectQuery } from "plumier"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
email: string
@Column()
name: string
@Column()
deleted: boolean
@Column()
createdAt: Date
}
export class UsersController {
/**
* Query Parser https://plumierjs.com/query-parser
*
* Parse user query string for select, filter and order into mongoose query.
*
* Valid query:
* /users?select=email,name&filter=(deleted=false and name='john'*)&order=-createdAt
*/
@route.get("")
list(@selectParser(x => User) select: SelectQuery, @filterParser(x => User) filter: any, @orderParser(x => User) order: any) {
const repo = getRepository(User)
return repo.find({ where: filter, select: select.columns, relations: select.relations, order })
}
}
|
plumier/examples
|
04-first-class-entity/generic-controller-typeorm/src/controller/users-logs-controller.ts
|
<gh_stars>1-10
import { GenericController } from "@plumier/typeorm"
import { Log } from "../entity/logs-entity"
// create generic controller using many-to-one relation
// it will serve /users/:pid/logs
export class UsersLogsController extends GenericController([Log, "user"]){}
|
plumier/examples
|
08-complete-example/marketplace-api/src/_shared/entity-base.ts
|
<reponame>plumier/examples
import { authorize, entity } from "plumier"
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm"
@Entity()
export class EntityBase {
@PrimaryGeneratedColumn()
id: number
@authorize.readonly()
@CreateDateColumn()
createdAt: Date
@authorize.readonly()
@UpdateDateColumn()
updatedAt: Date
@authorize.readonly()
@entity.deleteColumn()
@Column({ default: false })
deleted: boolean
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/shops-users/shops-users-entity.ts
|
<reponame>plumier/examples
import { noop } from "@plumier/reflect"
import { api, authorize, ControllerBuilder, genericController, val } from "plumier"
import { Column, Entity, ManyToOne } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { Shop } from "../shops/shops-entity"
import { User } from "../users/users-entity"
@Entity()
export class ShopUser extends EntityBase {
@val.required()
@ManyToOne(x => User)
user: User
@authorize.readonly()
@ManyToOne(x => Shop)
shop:Shop
@val.enums(["ShopOwner", "ShopStaff"])
@Column({ default: "ShopStaff" })
role: "ShopOwner" | "ShopStaff"
}
|
plumier/examples
|
03-data-access/data-access-mongoose/src/entity/base-entity.ts
|
<filename>03-data-access/data-access-mongoose/src/entity/base-entity.ts
import { collection } from "@plumier/mongoose";
// you can define an entity base class to bring common properties
export class EntityBase {
@collection.id()
id:string
// property decorator receives mongoose schema type configuration
@collection.property({ default: false })
deleted: boolean
@collection.property()
createdAt: Date
}
|
plumier/examples
|
04-first-class-entity/custom-generic-controller-typeorm/src/controller/person-controller.ts
|
<filename>04-first-class-entity/custom-generic-controller-typeorm/src/controller/person-controller.ts<gh_stars>1-10
import { CustomGenericController } from "../custom-generic-controller";
import { User } from "../entity/users-entity";
// example usage of custom generic controller factory,
// we used user entity but set different route to avoid conflict
export class PersonController extends CustomGenericController(User, c => c.setPath("persons/:id")) { }
|
plumier/examples
|
08-complete-example/marketplace-api/test/user-orders.spec.ts
|
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createCart, createUser, ignore } from "./_helper"
const oIgnore = { ...ignore, date: expect.any(String), user: { ...ignore }, address: { ...ignore } }
afterEach(async () => {
await closeConnection()
})
describe("User Orders", () => {
it("Should able to list orders", async () => {
const app = await createApp({ mode: "production" })
const { user } = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: orders } = await supertest(app.callback())
.get(`/api/users/${user.id}/orders`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(orders.map((x: any) => ({ shop: x.shop.name, state: x.state }))).toMatchSnapshot()
})
it("Should not accessible by other user", async () => {
const app = await createApp({ mode: "production" })
const { user } = await createCart(app)
const otherUser = await createUser(app, { email: "<EMAIL>" })
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/users/${user.id}/orders`)
.set("Authorization", `Bearer ${otherUser.token}`)
.expect(403)
})
})
|
plumier/examples
|
04-first-class-entity/custom-generic-controller-typeorm/src/entity/users-entity.ts
|
<filename>04-first-class-entity/custom-generic-controller-typeorm/src/entity/users-entity.ts
import { entity, genericController } from "plumier"
import { Column, Entity, PrimaryGeneratedColumn, CreateDateColumn } from "typeorm"
@genericController()
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
email: string
@Column()
name: string
@entity.deleteColumn()
@Column()
deleted: boolean
@CreateDateColumn()
createdAt: Date
}
|
plumier/examples
|
02-controller/query-parser-mongoose/src/index.ts
|
import { MongooseFacility } from "@plumier/mongoose"
import Plumier, { WebApiFacility } from "plumier"
new Plumier()
.set(new WebApiFacility())
.set(new MongooseFacility({ uri: "mongodb://localhost:27017/query-parser" }))
.listen(8000)
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/users/users-entity.ts
|
import { noop } from "@plumier/reflect"
import { api, authorize, genericController, preSave, val } from "plumier"
import { Column, Entity, OneToMany } from "typeorm"
import bcrypt from "<PASSWORD>"
import { EntityBase } from "../../_shared/entity-base"
import { Order } from "../orders/order-entity"
import { ShippingAddress } from "../shipping-addresses/shipping-addresses-entity"
import { ShopUser } from "../shops-users/shops-users-entity"
// /api/users
@genericController(c => {
c.post().authorize("Public")
c.methods("Delete", "GetOne", "Patch", "Put").authorize("ResourceOwner")
c.getMany().authorize("Admin")
})
@api.tag("Users Management")
@Entity()
export class User extends EntityBase {
@authorize.read("ResourceOwner", "Admin")
@val.required()
@val.unique()
@val.email()
@Column()
email: string
@authorize.writeonly()
@val.required()
@Column()
password: string
@val.required()
@Column()
name: string
@authorize.write("Admin")
@authorize.read("ResourceOwner", "Admin")
@Column({ default: "User" })
role: "User" | "Admin"
// /api/users/{pid}/shops
@genericController(c => {
c.setPath("users/:pid/shops/:id")
c.getMany().authorize("ResourceOwner")
.transformer(UserShopDto, transformer)
c.mutators().ignore()
})
@authorize.none()
@api.tag("User Shop Management")
@OneToMany(x => ShopUser, x => x.user)
shops: ShopUser[]
// /api/users/{pid}/shipping-addresses
@genericController(c => {
c.setPath("users/:pid/shipping-addresses/:id")
c.all().authorize("ResourceOwner")
})
@api.tag("User Shipping Address Management")
@authorize.none()
@OneToMany(x => ShippingAddress, x => x.user)
address: ShippingAddress[]
// /api/users/{pid}/orders
@genericController(c => {
c.mutators().ignore()
c.accessors().authorize("ResourceOwner")
})
@api.tag("User Order Management")
@authorize.none()
@OneToMany(x => Order, x => x.user)
orders: Order[]
@preSave()
async hashPassword() {
if (this.password)
this.password = await bcrypt.hash(this.password, await bcrypt.genSalt())
}
}
const transformer = (x: ShopUser) => (<UserShopDto>{
shopId: x.shop.id,
name: x.shop.name,
role: x.role
})
export class UserShopDto {
@noop()
shopId: number
@noop()
name: string
@noop()
role: "ShopOwner" | "ShopStaff"
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/index.ts
|
import dotenv from "dotenv"
import createApp from "./app"
dotenv.config()
createApp()
.then(koa => koa.listen(process.env.PORT ?? 8000))
.catch(err => console.error(err))
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/products/products-policy.ts
|
<gh_stars>1-10
import { entityPolicy } from "plumier"
import { getRepository } from "typeorm"
import { Product } from "./products-entity"
import { ShopUser } from "../shops-users/shops-users-entity"
entityPolicy(Product)
.register("ShopOwner", async ({ user }, id) => {
const item = await getRepository(Product).findOne(id, { relations: ["shop", "shop.users"] })
const shopUser = await getRepository(ShopUser).findOne({ where: { shop: item?.shop.id, user: user?.userId }, cache: true })
return shopUser?.role === "ShopOwner"
})
.register("ShopStaff", async ({ user }, id) => {
const item = await getRepository(Product).findOne(id, { relations: ["shop", "shop.users"] })
const shopUser = await getRepository(ShopUser).findOne({ where: { shop: item?.shop.id, user: user?.userId }, cache: true })
return shopUser?.role === "ShopStaff"
})
|
plumier/examples
|
04-first-class-entity/generic-controller-typeorm/src/entity/users-entity.ts
|
<gh_stars>1-10
import { entity, genericController } from "plumier"
import { Column, Entity, PrimaryGeneratedColumn, OneToMany } from "typeorm"
import { Email } from "./emails-entity"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column()
name: string
@OneToMany(x => Email, x => x.user)
emails: Email
// mark property as delete column,
// DELETE /users/:id will not delete the record permanently
@entity.deleteColumn()
@Column({ default: false })
deleted: boolean
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/shops.spec.ts
|
<filename>08-complete-example/marketplace-api/test/shops.spec.ts
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createUser, ignore, userToken } from "./_helper"
afterEach(async () => {
await closeConnection()
})
describe("Shop", () => {
it("Should not able to create shop without authenticated", async () => {
const app = await createApp({ mode: "production" })
await supertest(app.callback())
.post("/api/shops")
.send({ name: "<NAME>" })
.expect(401)
})
it("Should able to register for any login user", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
await supertest(app.callback())
.post("/api/shops")
.send({ name: "<NAME>" })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
})
it("Should assign person who register as owner", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const { body } = await supertest(app.callback())
.post("/api/shops")
.send({ name: "<NAME>" })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: result } = await supertest(app.callback())
.get(`/api/shops/${body.id}/users`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(result[0]).toMatchSnapshot({ userId: expect.any(Number) })
})
it("Should restrict other user to modify other shop", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const { body } = await supertest(app.callback())
.post("/api/shops")
.send({ name: "<NAME>" })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.patch(`/api/shops/${body.id}`)
.set("Authorization", `Bearer ${userToken}`)
.expect(403)
})
})
|
plumier/examples
|
04-first-class-entity/generic-controller-typeorm/src/controller/users-emails-controller.ts
|
import { GenericController } from "@plumier/typeorm"
import { User } from "../entity/users-entity"
// create generic controller using one-to-many relation
// it will serve /users/:pid/emails
export class UsersEmailsController extends GenericController([User, "emails"]){}
|
plumier/examples
|
02-controller/routing/src/controller/03-restful-controller.ts
|
<filename>02-controller/routing/src/controller/03-restful-controller.ts<gh_stars>1-10
/**
* With combination of route configurations we can create restful route
*
* POST /users
* GET /users?limit&offset
* GET /users/:id
* PUT /users/:id
* PATCH /users/:id
* DELETE /users/:id
*/
import { meta, route } from "plumier";
export class User {
@meta.property()
userName:string
@meta.property()
name:string
}
export class UsersController {
// POST /users
@route.post("")
save(data:User){
return {}
}
// GET /users
@route.get("")
list(limit:number, offset:number){
return {}
}
// GET /users/:id
@route.get(":id")
get(id:string){
return {}
}
// PUT /users/:id
@route.put(":id")
replace(id:string){
return {}
}
// PATCH /users/:id
@route.patch(":id")
modify(id:string){
return {}
}
// DELETE /users/:id
@route.delete(":id")
delete(id:string){
return {}
}
}
|
plumier/examples
|
04-first-class-entity/custom-generic-controller-typeorm/src/index.ts
|
import { TypeORMFacility } from "@plumier/typeorm"
import Plumier, { WebApiFacility } from "plumier"
import { CustomControllerGeneric, CustomNestedControllerGeneric } from "./custom-generic-controller"
new Plumier()
.set(new WebApiFacility())
.set(new TypeORMFacility())
.set({ genericController: [CustomControllerGeneric, CustomNestedControllerGeneric] })
.listen(8000)
|
plumier/examples
|
02-controller/routing/src/index.ts
|
import Plumier, { WebApiFacility } from "plumier"
new Plumier()
.set(new WebApiFacility())
.listen(8000)
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/products/products-entity.ts
|
<reponame>plumier/examples<gh_stars>1-10
import { api, authorize, genericController, val } from "plumier"
import { Column, Entity, JoinTable, ManyToMany, ManyToOne } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { Image } from "../images/images-entity"
import { Shop } from "../shops/shops-entity"
// /api/products
@genericController(c => {
c.mutators().ignore()
})
@api.tag("Product List")
@Entity()
export class Product extends EntityBase {
@authorize.readonly()
@ManyToOne(x => Shop)
shop:Shop
@val.required()
@Column()
name:string
@authorize.read("ShopOwner", "ShopStaff", "Admin")
@Column()
basePrice:number
@val.required()
@Column()
price:number
@ManyToMany(x => Image)
@JoinTable()
images:Image[]
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/users-shops.spec.ts
|
<gh_stars>1-10
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createShop, createUser, ignore } from "./_helper"
afterEach(async () => {
await closeConnection()
})
describe("Shop User", () => {
it("Should able to add user by shop owner", async () => {
const app = await createApp({ mode: "production" })
const { owner: ali } = await createShop(app, {
shop: { name: "Ali Shop" },
owner: { email: "<EMAIL>" },
staffs: []
})
const { shop: cuteMart, owner: tia } = await createShop(app, {
shop: { name: "Tia Shop" },
owner: { email: "<EMAIL>" },
staffs: []
})
await supertest(app.callback())
.post(`/api/shops/${cuteMart.id}/users`)
.set("Authorization", `Bearer ${tia.token}`)
.send({ user: ali.id })
.expect(200)
const { body: result } = await supertest(app.callback())
.get(`/api/users/${ali.id}/shops`)
.set("Authorization", `Bearer ${ali.token}`)
.expect(200)
expect(result[0]).toMatchSnapshot({ shopId: expect.any(Number) })
expect(result[1]).toMatchSnapshot({ shopId: expect.any(Number) })
})
it("Should not accessible by other user", async () => {
const app = await createApp({ mode: "production" })
const { owner: ali, staffs } = await createShop(app, { shop: { name: "Ali Shop" }, owner: { email: "<EMAIL>" } })
await supertest(app.callback())
.get(`/api/users/${ali.id}/shops`)
.set("Authorization", `Bearer ${staffs[0].token}`)
.expect(403)
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/carts-items/carts-items-entity.ts
|
<gh_stars>1-10
import { authorize, meta, val } from "plumier"
import { Column, Entity, ManyToOne } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { Cart } from "../carts/carts-entity"
import { Product } from "../products/products-entity"
import { Shop } from "../shops/shops-entity"
@Entity()
export class CartItem extends EntityBase{
@authorize.readonly()
@ManyToOne(x => Cart)
cart:Cart
@authorize.readonly()
@ManyToOne(x => Shop)
shop:Shop
@val.required()
@ManyToOne(x => Product)
product:Product
@val.required()
@Column()
quantity:number
}
export class CartItemDto extends CartItem {
@meta.property()
subTotal:number
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/orders-items/order-item-policy.ts
|
<reponame>plumier/examples
import { entityPolicy } from "plumier"
import { getRepository } from "typeorm"
import { ShopUser } from "../shops-users/shops-users-entity"
import { OrderItem } from "./order-item-entity"
entityPolicy(OrderItem)
.register("ResourceOwner", async ({ user }, id) => {
const oRepo = getRepository(OrderItem)
const item = await oRepo.findOne(id, { relations: ["order.user"] })
return item?.deleted === false && item.order.user.id === user?.userId
})
.register("ShopOwner", async ({ user }, id) => {
const oRepo = getRepository(OrderItem)
const uRepo = getRepository(ShopUser)
const item = await oRepo.findOne(id, { relations: ["shop"] })
const uShop = await uRepo.findOne({ where: { shop: item?.shop.id, user: user?.userId } })
return item?.deleted === false && uShop?.role === "ShopOwner"
})
.register("ShopStaff", async ({ user }, id) => {
const oRepo = getRepository(OrderItem)
const uRepo = getRepository(ShopUser)
const item = await oRepo.findOne(id, { relations: ["shop"] })
const uShop = await uRepo.findOne({ where: { shop: item?.shop.id, user: user?.userId } })
return item?.deleted === false && uShop?.role === "ShopStaff"
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/orders/order-policy.ts
|
<filename>08-complete-example/marketplace-api/src/api/orders/order-policy.ts
import { entityPolicy } from "plumier";
import { getRepository } from "typeorm";
import { ShopUser } from "../shops-users/shops-users-entity";
import { Order } from "./order-entity";
entityPolicy(Order)
.register("ResourceOwner", async ({ user }, id) => {
const repo = getRepository(Order)
const order = await repo.findOne(id, { relations: ["user"] })
return order?.deleted === false && order.user.id === user?.userId
})
.register("ShopOwner", async ({ user }, id) => {
const oRepo = getRepository(Order)
const uRepo = getRepository(ShopUser)
const order = await oRepo.findOne(id, { relations: ["shop"] })
const uShop = await uRepo.findOne({ where: { shop: order?.shop.id, user: user?.userId } })
return order?.deleted === false && uShop?.role === "ShopOwner"
})
.register("ShopStaff", async ({ user }, id) => {
const oRepo = getRepository(Order)
const uRepo = getRepository(ShopUser)
const order = await oRepo.findOne(id, { relations: ["shop"] })
const uShop = await uRepo.findOne({ where: { shop: order?.shop.id, user: user?.userId } })
return order?.deleted === false && uShop?.role === "ShopStaff"
})
|
plumier/examples
|
05-security/basic-security/src/controller/private-controller.ts
|
<reponame>plumier/examples
import { authorize, bind, route } from "@plumier/core";
import { JwtClaims } from "plumier";
export class PrivateController {
/**
* This route only accessible by Admin
*/
@authorize.route("Admin")
@route.get()
admin() {
return { message: "Welcome Admin" }
}
/**
* This route only accessible by SuperAdmin
*/
@authorize.route("SuperAdmin")
@route.get()
superAdmin() {
return { message: "Welcome SuperAdmin" }
}
/**
* This route only accessible by User
*/
@authorize.route("User")
@route.get()
user() {
return { message: "Welcome User" }
}
/**
* This route only accessible by SuperAdmin and Admin
*/
@authorize.route("SuperAdmin", "Admin")
@route.get()
allAdmins() {
return { message: "Welcome Admins" }
}
/**
* This route accessible by any user
* we can get login user from controller using @bind.user()
*/
@route.get()
anyUser(@bind.user() user: JwtClaims) {
return { message: `Welcome ${user.role}` }
}
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/order-items.spec.ts
|
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createCart, createUser, omitKeys } from "./_helper"
const omit = (obj: any) => omitKeys(obj, ["createdAt", "updatedAt"])
afterEach(async () => {
await closeConnection()
})
describe("Order Items", () => {
it("Should accessible by resource owner", async () => {
const app = await createApp({ mode: "production" })
const { user, shops: [putra] } = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: orders } = await supertest(app.callback())
.get(`/api/shops/${putra.shop.id}/orders`)
.set("Authorization", `Bearer ${putra.staffs[0].token}`)
.expect(200)
const {body} = await supertest(app.callback())
.get(`/api/orders/${orders[0].id}/items`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(omit(body)).toMatchSnapshot()
})
it("Should accessible by shop staff", async () => {
const app = await createApp({ mode: "production" })
const { user, shops: [putra] } = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: orders } = await supertest(app.callback())
.get(`/api/shops/${putra.shop.id}/orders`)
.set("Authorization", `Bearer ${putra.staffs[0].token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/orders/${orders[0].id}/items`)
.set("Authorization", `Bearer ${putra.staffs[0].token}`)
.expect(200)
})
it("Should accessible by shop owner", async () => {
const app = await createApp({ mode: "production" })
const { user, shops: [putra] } = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: orders } = await supertest(app.callback())
.get(`/api/shops/${putra.shop.id}/orders`)
.set("Authorization", `Bearer ${putra.staffs[0].token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/orders/${orders[0].id}/items`)
.set("Authorization", `Bearer ${putra.owner.token}`)
.expect(200)
})
it("Should not accessible by other user", async () => {
const app = await createApp({ mode: "production" })
const { user, shops: [putra] } = await createCart(app)
const otherUser = await createUser(app, { email: "<EMAIL>" })
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: orders } = await supertest(app.callback())
.get(`/api/shops/${putra.shop.id}/orders`)
.set("Authorization", `Bearer ${putra.staffs[0].token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/orders/${orders[0].id}/items`)
.set("Authorization", `Bearer ${otherUser.token}`)
.expect(403)
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/carts/carts-entity.ts
|
<reponame>plumier/examples
import { authorize } from "@plumier/core"
import { api, genericController } from "plumier"
import { Column, Entity, ManyToOne, OneToMany } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { CartItem, CartItemDto } from "../carts-items/carts-items-entity"
import { ShippingAddress } from "../shipping-addresses/shipping-addresses-entity"
import { User } from "../users/users-entity"
@genericController(c => {
c.methods("Post", "Delete", "GetMany", "Put").ignore()
c.methods("Patch", "GetOne").authorize("ResourceOwner")
})
@api.tag("Shopping Cart")
@Entity()
export class Cart extends EntityBase {
@authorize.readonly()
@ManyToOne(x => User)
user: User
@ManyToOne(x => ShippingAddress)
address: ShippingAddress
@authorize.readonly()
@Column()
state: "Open" | "Closed"
@genericController(c => {
c.methods("Post").ignore()
c.accessors().transformer(CartItemDto, (x: CartItem) => ({ ...x, subTotal: x.quantity * x.product.price }))
.authorize("ResourceOwner")
c.methods("Put", "Patch", "Delete", "Post").authorize("ResourceOwner")
})
@api.tag("Shopping Cart")
@authorize.none()
@OneToMany(x => CartItem, x => x.cart)
items: CartItem[]
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/_helper.ts
|
<filename>08-complete-example/marketplace-api/test/_helper.ts
import dotenv from "dotenv"
import { sign } from "jsonwebtoken"
import { join } from "path"
import { JwtClaims } from "plumier"
import supertest from "supertest"
import { getConnection } from "typeorm"
import { Product } from "../src/api/products/products-entity"
import { Shop } from "../src/api/shops/shops-entity"
import { User } from "../src/api/users/users-entity"
dotenv.config({ path: join(__dirname, ".env-test") })
export function createToken(id: number, role: "User" | "Admin") {
return sign(<JwtClaims>{ userId: id, role }, process.env.PLUM_JWT_SECRET!)
}
export const ignoreProps = {
id: expect.any(Number),
createdAt: expect.any(String),
updatedAt: expect.any(String),
}
export const userToken = createToken(123, "User")
export const adminToken = createToken(456, "Admin")
export async function createUser(app: any, user: Partial<User> = {}) {
const { body } = await await supertest(app.callback())
.post("/api/users")
.set("Authorization", `Bearer ${adminToken}`)
.send({
email: user.email ?? "<EMAIL>",
password: user.password ?? "<PASSWORD>#",
name: user.name ?? "<NAME>",
role: user.role ?? "User"
}).expect(200)
const token = createToken(body.id, user.role ?? "User")
return { id: body.id, token }
}
interface CreateShopOption {
shop?: Partial<Shop>
owner?: Partial<User>
staffs?: Partial<User>[]
items?: Partial<Product>[]
}
export async function createShop(app: any, opt?: CreateShopOption) {
const option: CreateShopOption = {
staffs: [{ email: "<EMAIL>", name: "Putra Mahkota Staff" }],
items: [],
...opt,
}
const shopOwner = await createUser(app, option.owner)
const { body } = await supertest(app.callback())
.post("/api/shops")
.send({ name: "<NAME>", ...option.shop })
.set("Authorization", `Bearer ${shopOwner.token}`)
.expect(200)
const shopStaffs = []
for (const staff of option.staffs ?? []) {
const result = await createUser(app, staff)
shopStaffs.push(result)
await supertest(app.callback())
.post(`/api/shops/${body.id}/users`)
.send({ user: result.id })
.set("Authorization", `Bearer ${shopOwner.token}`)
.expect(200)
}
const shopProducts = []
for (const item of option.items ?? []) {
const { body: addedProduct } = await supertest(app.callback())
.post(`/api/shops/${body.id}/products`)
.send(item)
.set("Authorization", `Bearer ${shopOwner.token}`)
.expect(200)
shopProducts.push(addedProduct)
}
return { owner: shopOwner, staffs: shopStaffs, shop: <{ id: number }>body, products: shopProducts }
}
export async function createCart(app: any) {
const { products, ...putra } = await createShop(app, {
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500 },
{ name: "Li-Ion Battery", basePrice: 200, price: 250 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 900 },
]
})
const { products: aliItems, ...ali } = await createShop(app, {
shop: { name: "Ali Shop" },
owner: { email: "<EMAIL>" },
staffs: [],
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2100 },
{ name: "Li-Ion Battery", basePrice: 200, price: 210 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 800 },
]
})
const user = await createUser(app, { email: "<EMAIL>", name: "<NAME>" })
const { body: cart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[0].id, quantity: 1 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[1].id, quantity: 2 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[2].id, quantity: 2 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: aliItems[0].id, quantity: 1 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
// add shipping address
const { body: address } = await supertest(app.callback())
.post(`/api/users/${user.id}/shipping-addresses`)
.send({
address: "Br. Guntur Kemenuh Blahbatuh Gianyar",
city: "Gianyar",
country: "Indonesia",
zipCode: "80281",
})
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.patch(`/api/carts/${cart.id}`)
.send({ address: address.id })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
return { id: cart.id, user, shops: [putra, ali] }
}
export async function closeConnection() {
const con = getConnection()
if (con.isConnected)
await con.close()
}
export const ignore = {
createdAt: expect.any(String),
updatedAt: expect.any(String),
id: expect.any(Number)
}
export const omitKeys = (obj: any, keys: string[]): any => obj !== Object(obj)
? obj
: Array.isArray(obj)
? obj.map((item) => omitKeys(item, keys))
: Object.keys(obj)
.filter((k) => !keys.includes(k))
.reduce((acc, x) => Object.assign(acc, { [x]: omitKeys(obj[x], keys) }), {})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/carts-items/carts-items-policy.ts
|
<reponame>plumier/examples
import { entityPolicy } from "plumier"
import { getRepository } from "typeorm"
import { CartItem } from "./carts-items-entity"
entityPolicy(CartItem)
// user become CartOwner only when the state is Open, after that he not authorized to access the cart
.register("ResourceOwner", async ({ user }, id) => {
const item = await getRepository(CartItem).findOne(id, { relations: ["cart"], cache: true })
return item?.cart.state === "Open" && item?.cart.user.id === user?.userId
})
|
plumier/examples
|
04-first-class-entity/first-class-entity-typeorm/src/controller/emails-entity.ts
|
<gh_stars>1-10
import { entity, genericController } from "plumier"
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, CreateDateColumn } from "typeorm"
import { User } from "./users-entity"
@Entity()
export class Email {
@PrimaryGeneratedColumn()
id: number
@Column()
email: string
@Column()
description:string
@Column()
primary:boolean
@ManyToOne(x => User)
user:User
}
|
plumier/examples
|
02-controller/query-parser-mongoose/src/controller/users-controller.ts
|
<filename>02-controller/query-parser-mongoose/src/controller/users-controller.ts<gh_stars>1-10
import model, { collection } from "@plumier/mongoose"
import { filterParser, meta, orderParser, route, selectParser, SelectQuery } from "plumier"
@collection()
export class User {
@meta.property()
email: string
@meta.property()
name: string
@meta.property()
deleted:boolean
@meta.property()
createdAt:Date
}
export class UsersController {
/**
* Query Parser https://plumierjs.com/query-parser
*
* Parse user query string for select, filter and order into mongoose query.
*
* Valid query:
* /users?select=email,name&filter=(deleted=false and name='john'*)&order=-createdAt
*/
@route.get("")
list(@selectParser(x => User) select:SelectQuery, @filterParser(x => User) filter:any, @orderParser(x => User) order:any){
const UserModel = model(User)
return UserModel.find(filter, select.columns)
.populate(select.relations)
.sort(order)
}
}
|
plumier/examples
|
07-serve-static-and-file-upload/file-upload-s3/src/index.ts
|
<filename>07-serve-static-and-file-upload/file-upload-s3/src/index.ts
import Plumier, { WebApiFacility } from "plumier"
new Plumier()
// enable the multipart form
.set(new WebApiFacility({ bodyParser: { multipart: true } }))
.listen(8000)
|
plumier/examples
|
08-complete-example/marketplace-api/test/shops-products.spec.ts
|
import { join } from "path"
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createShop, ignore, userToken } from "./_helper"
afterEach(async () => {
await closeConnection()
})
describe("Shop Item", () => {
it("Should able adding item by staff", async () => {
const app = await createApp({ mode: "production" })
const { staffs, shop } = await createShop(app)
await supertest(app.callback())
.post(`/api/shops/${shop.id}/products`)
.send({ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500 })
.set("Authorization", `Bearer ${staffs[0]?.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/shops/${shop.id}/products`)
.set("Authorization", `Bearer ${staffs[0]?.token}`)
.expect(200)
expect(body[0]).toMatchSnapshot(ignore)
})
it("Should hide basePrice for non shop staff", async () => {
const app = await createApp({ mode: "production" })
const { staffs, shop } = await createShop(app)
await supertest(app.callback())
.post(`/api/shops/${shop.id}/products`)
.send({ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500 })
.set("Authorization", `Bearer ${staffs[0]?.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/shops/${shop.id}/products`)
.set("Authorization", `Bearer ${userToken}`)
.expect(200)
expect(body[0]).toMatchSnapshot(ignore)
})
it("Should able adding images", async () => {
const app = await createApp({ mode: "production" })
const { staffs, shop } = await createShop(app)
const { body: img1 } = await supertest(app.callback())
.post(`/api/images/upload`)
.attach("file", join(__dirname, "image/landscape.jpeg"))
.set("Authorization", `Bearer ${staffs[0].token}`)
.expect(200)
const { body: img2 } = await supertest(app.callback())
.post(`/api/images/upload`)
.attach("file", join(__dirname, "image/landscape.jpeg"))
.set("Authorization", `Bearer ${staffs[0].token}`)
.expect(200)
const { body: prod } = await supertest(app.callback())
.post(`/api/shops/${shop.id}/products`)
.send({ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500, images: [img1.id, img2.id] })
.set("Authorization", `Bearer ${staffs[0]?.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/shops/${shop.id}/products/${prod.id}?select=id,name,price,images`)
.set("Authorization", `Bearer ${staffs[0]?.token}`)
.expect(200)
const { images, ...product } = body
expect(product).toMatchSnapshot()
expect(images[0]).toMatchSnapshot({ ...ignore, size: expect.any(Number) })
expect(images[1]).toMatchSnapshot({ ...ignore, size: expect.any(Number) })
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/shipping-addresses/shipping-addresses-policy.ts
|
<gh_stars>1-10
import { entityPolicy } from "plumier"
import { getRepository } from "typeorm"
import { ShippingAddress } from "./shipping-addresses-entity"
entityPolicy(ShippingAddress)
.register("ResourceOwner", async ({ user }, id) => {
const address = await getRepository(ShippingAddress).findOne(id, { relations: ["user"], cache: true })
return address?.user.id === user?.userId
})
|
plumier/examples
|
05-security/basic-security/src/index.ts
|
import { JwtAuthFacility } from "@plumier/jwt"
import Plumier, { WebApiFacility } from "plumier"
import dotenv from "dotenv"
dotenv.config()
new Plumier()
.set(new WebApiFacility())
.set(new JwtAuthFacility())
.listen(8000)
|
plumier/examples
|
04-first-class-entity/first-class-entity-mongoose/src/controller/logs-entity.ts
|
import { collection } from "@plumier/mongoose"
import { genericController } from "plumier"
import { User } from "./users-entity"
@collection()
export class Log {
@collection.id()
id:string
@collection.property()
message: string
// create generic controller from many-to-one
// it will generated into /users/:pid/logs
@genericController()
@collection.ref(x => User)
user:User
}
|
plumier/examples
|
05-security/social-login/src/index.ts
|
<filename>05-security/social-login/src/index.ts
import { ServeStaticFacility } from "@plumier/serve-static"
import {
FacebookOAuthFacility,
GitHubOAuthFacility,
GitLabOAuthFacility,
GoogleOAuthFacility,
OAuthUser,
redirectUri,
TwitterOAuthFacility,
} from "@plumier/social-login"
import dotenv from "dotenv"
import { join } from "path"
import Plumier, { bind, response, route, WebApiFacility, LoggerFacility } from "plumier"
dotenv.config()
export class AuthController {
@route.get("/")
index() {
return response.file(join(__dirname, "./www/index.html"))
}
/**
* /auth/callback
* is the global redirect uri, used for all installed social login facility
*/
@redirectUri()
callback(@bind.oAuthUser() user: OAuthUser) {
// send response back from popup window to main window with success message
// and user information
return response.postMessage({ status: "Success", user })
}
}
new Plumier()
.set(new WebApiFacility())
.set(new LoggerFacility())
// serve the static files (by default under www) directory
.set(new ServeStaticFacility())
.set(new FacebookOAuthFacility())
.set(new GoogleOAuthFacility())
.set(new GitHubOAuthFacility())
.set(new GitLabOAuthFacility())
.set(new TwitterOAuthFacility())
.listen(8000)
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/auth/auth-policy.ts
|
<filename>08-complete-example/marketplace-api/src/api/auth/auth-policy.ts<gh_stars>1-10
import { authPolicy } from "plumier";
authPolicy()
// register Admin role
.register("Admin", ({ user }) => user?.role === "Admin")
// register User role
.register("User", ({ user }) => user?.role === "User")
// global authorization policy, see how it used in JwtAuthFacility
.register("AnyUser", ({ user }) => {
// forbid non login user
if (!user) return false
// forbid refresh token
if (user.refresh) return false
return true
})
// refresh token policy, see how it used in AuthController.refresh
.register("RefreshToken", ({ user }) => {
// only allow if jwt claim contains refresh token
return !!user?.refresh
})
|
plumier/examples
|
08-complete-example/marketplace-api/test/users.spec.ts
|
<reponame>plumier/examples<filename>08-complete-example/marketplace-api/test/users.spec.ts<gh_stars>1-10
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createToken, ignore, userToken } from "./_helper"
afterEach(async () => {
await closeConnection()
})
describe("User", () => {
it("Should able to register by public", async () => {
const app = await createApp({ mode: "production" })
await supertest(app.callback())
.post("/api/users")
.send({ name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>" })
.expect(200)
})
it("Should restrict to specify Role", async () => {
const app = await createApp({ mode: "production" })
await supertest(app.callback())
.post("/api/users")
.send({ name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>", role: "Admin" })
.expect(401)
})
it("Should readable by the owner", async () => {
const app = await createApp({ mode: "production" })
const { body } = await supertest(app.callback())
.post("/api/users")
.send({ name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>" })
.expect(200)
const token = createToken(body.id, "User")
const { body: result } = await supertest(app.callback())
.get(`/api/users/${body.id}`)
.set("Authorization", `Bearer ${token}`)
.expect(200)
expect(result).toMatchSnapshot(ignore)
})
it("Should only editable by the owner itself", async () => {
const app = await createApp({ mode: "production" })
const { body } = await supertest(app.callback())
.post("/api/users")
.send({ name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>" })
.expect(200)
const token = createToken(body.id, "User")
await supertest(app.callback())
.patch(`/api/users/${body.id}`)
.send({ name: "John" })
.set("Authorization", `Bearer ${userToken}`)
.expect(403)
await supertest(app.callback())
.patch(`/api/users/${body.id}`)
.send({ name: "John" })
.set("Authorization", `Bearer ${token}`)
.expect(200)
})
it("Should only delete-able by the owner itself", async () => {
const app = await createApp({ mode: "production" })
const { body } = await supertest(app.callback())
.post("/api/users")
.send({ name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>" })
.expect(200)
const token = createToken(body.id, "User")
await supertest(app.callback())
.delete(`/api/users/${body.id}`)
.set("Authorization", `Bearer ${userToken}`)
.expect(403)
await supertest(app.callback())
.delete(`/api/users/${body.id}`)
.set("Authorization", `Bearer ${token}`)
.expect(200)
})
})
|
plumier/examples
|
01-project-layout/file-layout-modular/src/api/users-logs/users-logs-controller.ts
|
import { route } from "plumier"
import { Log } from "./users-logs-entity"
@route.root("user/:uid/logs")
export class UsersLogsController {
// POST /users/:uid/logs
@route.post("")
save(uid:string, data:Log){
return {}
}
// GET /users/:uid/logs
@route.get("")
list(uid:string, limit:number, offset:number){
return {}
}
// GET /users/:uid/logs/:id
@route.get(":id")
get(uid:string, id:string){
return {}
}
// PUT /users/:uid/logs/:id
@route.put(":id")
replace(uid:string, id:string){
return {}
}
// PATCH /users/:uid/logs/:id
@route.patch(":id")
modify(uid:string, id:string){
return {}
}
// DELETE /users/:uid/logs/:id
@route.delete(":id")
delete(uid:string, id:string){
return {}
}
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/carts-items.spec.ts
|
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createShop, createUser, ignore, omitKeys } from "./_helper"
const omit = (obj: any) => omitKeys(obj, ["createdAt", "updatedAt"])
afterEach(async () => {
await closeConnection()
})
describe("Charts Items", () => {
it("Should add item properly", async () => {
const app = await createApp({ mode: "production" })
const { products } = await createShop(app, {
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500 },
{ name: "Li-Ion Battery", basePrice: 200, price: 250 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 900 },
]
})
const user = await createUser(app, { email: "<EMAIL>", name: "<NAME>" })
const { body: cart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[0].id, quantity: 1 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[1].id, quantity: 2 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[2].id, quantity: 2 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/carts/${cart.id}/items`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(omit(body)).toMatchSnapshot()
})
it("Should merge item quantity when added twice", async () => {
const app = await createApp({ mode: "production" })
const { products } = await createShop(app, {
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500 },
{ name: "Li-Ion Battery", basePrice: 200, price: 250 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 900 },
]
})
const user = await createUser(app, { email: "<EMAIL>", name: "<NAME>" })
const { body: cart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[0].id, quantity: 3 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: products[0].id, quantity: 2 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/carts/${cart.id}/items`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(omit(body)).toMatchSnapshot()
})
it("Should able to add from multiple shops", async () => {
const app = await createApp({ mode: "production" })
const { products: putraItems } = await createShop(app, {
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500 },
{ name: "Li-Ion Battery", basePrice: 200, price: 250 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 900 },
]
})
const { products: aliItems } = await createShop(app, {
shop: { name: "Ali Shop" },
owner: { email: "<EMAIL>" },
staffs: [],
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2100 },
{ name: "Li-Ion Battery", basePrice: 200, price: 210 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 800 },
]
})
const user = await createUser(app, { email: "<EMAIL>", name: "<NAME>" })
const { body: cart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: putraItems[0].id, quantity: 1 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.post(`/api/carts/${cart.id}/items`)
.send({ product: aliItems[0].id, quantity: 1 })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/carts/${cart.id}/items`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(omit(body)).toMatchSnapshot()
})
it("Should not accessible by other user", async () => {
const app = await createApp({ mode: "production" })
const jane = await createUser(app, { email: "<EMAIL>", name: "<NAME>" })
const john = await createUser(app, { email: "<EMAIL>" })
const { body: cart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${jane.token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/carts/${cart.id}/items`)
.set("Authorization", `Bearer ${john.token}`)
.expect(403)
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/shipping-addresses/shipping-addresses-entity.ts
|
import { val } from "@plumier/validator"
import { authorize, genericController } from "plumier"
import { Column, Entity, ManyToOne } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { User } from "../users/users-entity"
@Entity()
export class ShippingAddress extends EntityBase {
@authorize.readonly()
@ManyToOne(x => User)
user:User
@val.required()
@Column()
address: string
@val.required()
@Column()
city:string
@val.required()
@Column()
country: string
@val.required()
@Column()
zipCode: string
}
|
plumier/examples
|
02-controller/query-parser-typeorm/src/index.ts
|
import { TypeORMFacility } from "@plumier/typeorm"
import Plumier, { WebApiFacility } from "plumier"
new Plumier()
.set(new WebApiFacility())
.set(new TypeORMFacility())
.listen(8000)
|
plumier/examples
|
01-project-layout/file-layout-modular/src/api/users-logs/users-logs-entity.ts
|
import { meta } from "plumier"
export class Log {
@meta.property()
message:string
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/images/images-controller.ts
|
<gh_stars>1-10
import { type } from "@plumier/reflect"
import { api, bind, FormFile, JwtClaims, route, val } from "plumier"
import { getRepository } from "typeorm"
import { Image } from "./images-entity"
@api.tag("Image Management")
@route.root("images")
export class ImagesController {
@route.post()
@type({ id: Number })
async upload(@val.required() @val.image("1MB") file: FormFile, @bind.user() user: JwtClaims) {
// usually we push file to cloud storage such as Amazon S3 or Google Storage Bucket
// example https://github.com/plumier/examples/tree/master/07-serve-static-and-file-upload/file-upload-s3
const imageRepo = getRepository(Image)
const image = await imageRepo.save({
owner: { id: user.userId },
name: file.name,
mimeType: file.type,
size: file.size,
url: "https://image.com/image.jpg"
})
return { id: image.id }
}
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/shops-users.spec.ts
|
<filename>08-complete-example/marketplace-api/test/shops-users.spec.ts
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createShop, createUser, ignore } from "./_helper"
afterEach(async () => {
await closeConnection()
})
describe("Shop User", () => {
it("Should able to add user by shop owner", async () => {
const app = await createApp({ mode: "production" })
const { shop, owner } = await createShop(app)
const otherUser = await createUser(app, { name: "<NAME>", email: "<EMAIL>" })
await supertest(app.callback())
.post(`/api/shops/${shop.id}/users`)
.set("Authorization", `Bearer ${owner.token}`)
.send({ user: otherUser.id })
.expect(200)
const { body: result } = await supertest(app.callback())
.get(`/api/shops/${shop.id}/users`)
.set("Authorization", `Bearer ${owner.token}`)
.expect(200)
expect(result[1]).toMatchSnapshot({ userId: expect.any(Number) })
})
it("Should restrict modify shop user by ShopStaff", async () => {
const app = await createApp({ mode: "production" })
const { shop, owner } = await createShop(app)
const otherUser = await createUser(app, { name: "<NAME>", email: "<EMAIL>" })
const { body } = await supertest(app.callback())
.post(`/api/shops/${shop.id}/users`)
.set("Authorization", `Bearer ${owner.token}`)
.send({ user: otherUser.id })
.expect(200)
await supertest(app.callback())
.patch(`/api/shops/${shop.id}/users/${body.id}`)
.send({ role: "ShopOwner" })
.set("Authorization", `Bearer ${otherUser.token}`)
.expect(403)
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/carts-items/carts-items-controller.ts
|
import { api, authorize, entityProvider, HttpStatusError, route, val } from "plumier"
import { getRepository } from "typeorm"
import { Cart } from "../carts/carts-entity"
import { Product } from "../products/products-entity"
import { CartItem } from "./carts-items-entity"
@api.tag("Shopping Cart")
@route.root("carts/:pid/items")
@authorize.route("ResourceOwner")
export class CartItemController {
@route.post("")
@entityProvider(Cart, "pid")
async save(@val.required() pid: number, data: CartItem) {
const cartItemRepo = getRepository(CartItem)
const cartRepo = getRepository(Cart)
const itemRepo = getRepository(Product)
const cart = await cartRepo.findOne(pid)
if (!cart) throw new HttpStatusError(404, "Cart not found")
const item = await itemRepo.findOne(data.product.id, { relations: ["shop"] })
if (!item) throw new HttpStatusError(400, "Invalid item id provided")
const exists = await cartItemRepo.findOne({ where: { cart: cart.id, product: item.id } })
if (exists) {
exists.quantity += data.quantity
await cartItemRepo.save(exists)
return exists
}
else {
const inserted = await cartItemRepo.save({ ...data, cart: { id: cart.id }, shop: item.shop })
return { id: inserted.id }
}
}
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/images/images-entity.ts
|
import { authorize, val } from "plumier"
import { Column, Entity, ManyToOne } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { User } from "../users/users-entity"
@Entity()
export class Image extends EntityBase {
@val.required()
@Column()
name: string
@authorize.readonly()
@Column()
mimeType: string
@authorize.readonly()
@Column()
size: number
@authorize.readonly()
@ManyToOne(x => User)
owner: User
@authorize.readonly()
@Column()
url: string
}
|
plumier/examples
|
04-first-class-entity/first-class-entity-mongoose/src/controller/emails-entity.ts
|
import { collection } from "@plumier/mongoose"
import { User } from "./users-entity"
@collection()
export class Email {
@collection.id()
id: string
@collection.property()
email: string
@collection.property()
description: string
@collection.property()
primary: boolean
@collection.ref(x => User)
user: User
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/carts/carts-controller.ts
|
import { api, bind, HttpStatusError, JwtClaims, meta, route } from "plumier"
import { getRepository } from "typeorm"
import { OrderItem } from "../orders-items/order-item-entity"
import { Order } from "../orders/order-entity"
import { Cart } from "./carts-entity"
@api.tag("Shopping Cart")
export class CartsController {
@route.ignore()
private async getOpen(user: JwtClaims, relations: string[] = []) {
const repo = getRepository(Cart)
const openCart = await repo.findOne({
where: { user: user.userId, state: "Open", deleted: false },
relations
})
return openCart ?? await repo.save({ state: "Open", user: { id: user.userId } })
}
@route.get()
@meta.type({ id: Number })
async open(@bind.user() user: JwtClaims) {
const { id } = await this.getOpen(user)
return { id }
}
@route.post()
async checkout(@bind.user() user: JwtClaims) {
const cartRepo = getRepository(Cart)
const orderRepo = getRepository(Order)
const oItmRepo = getRepository(OrderItem)
const cart = await this.getOpen(user, ["address", "items", "items.product", "items.product.shop"])
if (!cart.address)
throw new HttpStatusError(422, "Shipping address is required")
const orders: { [key: number]: Order } = {}
for (const item of cart.items) {
const shopId = item.product.shop.id
let order = orders[shopId]
if (!order) {
order = await orderRepo.save({
address: cart.address,
shop: { id: shopId },
state: "ReceivedBySeller",
user: { id: user.userId }
})
orders[shopId] = order
}
await oItmRepo.save({
order,
price: item.product.price,
product: item.product,
quantity: item.quantity,
shop: item.product.shop
})
}
await cartRepo.save({ ...cart, state: "Closed" })
}
}
|
plumier/examples
|
02-controller/validation/src/controller/users-controller.ts
|
import { route, val } from "plumier"
export class User {
/**
* Apply validator on property to validate its value
*/
@val.email()
@val.required()
email: string
@val.length({ min: 5, max: 128 })
name: string
}
export class UsersController {
@route.post("")
save(data: User) {
return {}
}
/**
* Its also possible to validate action parameter
*/
@route.get(":id")
get(@val.required() id: string) {
return {}
}
}
|
plumier/examples
|
04-first-class-entity/custom-generic-controller-typeorm/src/custom-generic-controller.ts
|
<filename>04-first-class-entity/custom-generic-controller-typeorm/src/custom-generic-controller.ts<gh_stars>1-10
import { createGenericControllerTypeORM, TypeORMControllerGeneric, TypeORMNestedControllerGeneric } from "@plumier/typeorm";
import { generic, type } from "@plumier/reflect"
import { meta } from "@plumier/core";
import { SelectQuery } from "plumier";
import { Context } from "koa"
@generic.parameter("T")
export class PaginatedResponse<T> {
@type(["T"])
result: T[]
@meta.property()
offset: number
@meta.property()
limit: number
@meta.property()
total: number
}
export class CustomControllerGeneric<T, TID> extends TypeORMControllerGeneric<T, TID> {
@type(PaginatedResponse, "T")
async list(offset: number | undefined, limit: number | undefined, filter: any, select: SelectQuery, order: string, ctx: Context): Promise<any> {
const result = await super.list(offset, limit, filter, select, order, ctx)
return <PaginatedResponse<T>>{
result, offset, limit, total: await this.repo.count(filter ?? {})
}
}
}
export class CustomNestedControllerGeneric<P, T, PID, TID> extends TypeORMNestedControllerGeneric<P, T, PID, TID>{
@type(PaginatedResponse, "T")
async list(pid: PID, offset: number | undefined, limit: number | undefined, filter: any, select: SelectQuery, order: string, ctx: Context): Promise<any> {
const result = await super.list(pid, offset, limit, filter, select, order, ctx)
return <PaginatedResponse<T>>{
result, offset, limit, total: await this.repo.count(filter ?? {})
}
}
}
/**
* Since we used custom generic controller, we can't use GenericController() factory anymore,
* because it uses the default generic controllers.
* Instead, we create a new generic controller factory.
*/
export const CustomGenericController = createGenericControllerTypeORM([CustomControllerGeneric, CustomNestedControllerGeneric])
|
plumier/examples
|
06-swagger/swagger/src/controller/logs-controller.ts
|
import { api, meta, route, val } from "@plumier/core"
export class Log {
@meta.property()
id: number
@meta.property()
message: string
@meta.property()
date: Date
/**
* Define enum to get dropdown input on swagger ui
*/
@val.enums(["Deleted", "Inactive"])
status: "Active" | "Inactive"
}
export class LogsController {
/**
* Description can be applied on action and parameters
*/
@api.description("Save log to the database")
@route.post("")
save(data: Log) {
return { success: true }
}
/**
* Define the return type of method to get proper response schema.
* (Only required when return type is generic type or array)
*
* Enum also can be applied directly on parameter which will be the query string
*/
@meta.type(Log)
@route.get(":id")
async get(id:number, @val.enums(["Active", "Inactive"]) state:"Active" | "Inactive"):Promise<Log> {
return <Log>{}
}
}
|
plumier/examples
|
05-security/entity-policy/src/controller/auth-controller.ts
|
import { sign } from "jsonwebtoken"
import { authorize, HttpStatusError, JwtClaims, route } from "plumier"
declare module "plumier" {
interface JwtClaims {
userId: number,
role: "Admin" | "SuperAdmin" | "User"
}
}
export class AuthController {
@authorize.route("Public")
@route.post()
login(username: string, password: string) {
if (username !== "demo" || password !== "<PASSWORD>")
throw new HttpStatusError(402, "Invalid username or password")
const token = sign(<JwtClaims>{ userId: 1234, role: "User" }, process.env.PLUM_JWT_SECRET!)
return { token }
}
}
|
plumier/examples
|
01-project-layout/file-layout-single-file/src/index.ts
|
<reponame>plumier/examples
import Plumier, { route, WebApiFacility } from "plumier";
// controller
// keep in mind all controllers need to be exported
export class UsersController {
@route.get()
get() {
return {}
}
}
// entry point application
new Plumier()
.set(new WebApiFacility())
.listen(8000)
|
plumier/examples
|
04-first-class-entity/generic-controller-typeorm/src/entity/logs-entity.ts
|
<filename>04-first-class-entity/generic-controller-typeorm/src/entity/logs-entity.ts<gh_stars>1-10
import { entity, genericController } from "plumier"
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, CreateDateColumn } from "typeorm"
import { User } from "./users-entity"
@Entity()
export class Log {
@PrimaryGeneratedColumn()
id: number
@Column()
message: string
@ManyToOne(x => User)
user: User
}
|
plumier/examples
|
02-controller/routing/src/controller/01-basic-controller.ts
|
import { route } from "@plumier/core";
/**
* Basic route generation.
*
* Rout by default generated based on controller name, action name, and action parameter names
*/
export class RoutingController {
/**
* Default Route
*
* By default when no parameter provided generated into /controller/action?param¶m¶m
*
* Generated into:
* GET /routing/simple?par1=lorem&par2=1234
*/
@route.get()
simple(par1: string, par2: number) {
return {}
}
/**
* Action Override
*
* When parameter provided, action name changed with the parameter provided
*
* Generated into:
* GET /routing/action/override?par1=lorem&par2=1234
*/
@route.get("action/override")
actionOvr(par1: string, par2: number) {
return {}
}
/**
* Action Override With Parameter
*
* Route parameter (start with :) can be provided
*
* Generated into:
* GET /routing/action/:id/override?par1=lorem&par2=1234
*/
@route.get("action/:id/override")
actionOvrPar(id: string, par1: string, par2: number) {
return {}
}
/**
* Absolute Route
*
* When start with slash (/) controller name (all preceding path) will be ignored
*
* Generated into:
* GET /absolute/route?par1=lorem&par2=1234
*/
@route.get("/absolute/route")
absolute(par1: string, par2: number) {
return {}
}
/**
* Ignore action name
*
* When provided empty string, action name will be ignored
*
* Generated into:
* GET /routing?par1=lorem&par2=1234
*/
@route.get("")
noName(par1: string, par2: number) {
return {}
}
/**
* Multiple Routes
*
* When provided multiple decorators, it generated into multiple routes
*
* Generated into:
* GET /routing/multiple/one?par1=lorem&par2=1234
* GET /routing/multiple/two?par1=lorem&par2=1234
*/
@route.get("multiple/one")
@route.get("multiple/two")
multiple(par1: string, par2: number) {
return {}
}
}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/shops-users/shops-users-policy.ts
|
import { entityPolicy } from "plumier"
import { getRepository } from "typeorm"
import { ShopUser } from "./shops-users-entity"
entityPolicy(ShopUser)
.register("ShopOwner", async ({ user }, id) => {
const shopUser = await getRepository(ShopUser)
.findOne(id, { relations: ["user"], cache: true })
return shopUser?.deleted === false && shopUser?.user.id === user?.userId && shopUser?.role === "ShopOwner"
})
.register("ShopStaff", async ({ user }, id) => {
const shopUser = await getRepository(ShopUser)
.findOne(id, { relations: ["user"], cache: true })
return shopUser?.deleted === false && shopUser?.user.id === user?.userId && shopUser?.role === "ShopStaff"
})
|
plumier/examples
|
03-data-access/data-access-mongoose/src/controller/users-controller.ts
|
<gh_stars>1-10
import { route } from "@plumier/core";
import model from "@plumier/mongoose";
import { User } from "../entity/users-entity";
export class UsersController {
@route.post("")
save(data:User) {
// create mongoose model using model factory like below
const UserModel = model(User)
return new UserModel(data).save()
}
}
|
plumier/examples
|
05-security/entity-policy/src/policy/main-policy.ts
|
import { authPolicy, entityPolicy } from "plumier";
import { Email } from "../entity/emails-entity";
import { User } from "../entity/users-entity";
import { getRepository } from "typeorm"
/**
* Here is the global policy (application wide policy),
* This policy can be applied globally and also can be use to secure entities
*
* This part already explained on `basic-security` example
*/
authPolicy()
.register("Admin", ctx => ctx.user?.role === "Admin")
.register("SuperAdmin", ctx => ctx.user?.role === "SuperAdmin")
.register("User", ctx => ctx.user?.role === "User")
/**
* Here we define policy to secure our entity using entity policy.
* Entity policy is a custom auth policy which provide function to secure
* entity based on its ID. Entity policy can be applied on the generated routes,
* or on entity property to restrict access (read/write) to entity property.
* Policy file can be place anywhere on the project, here in this example
* we put it on single place to easier to understand
*/
/**
* based on our rules defined on readme file.
*
* * User entity
* * Everyone (Public) can register as user
* * Only the owner of the data can modify/delete
* * Only the owner of the data can see the `dob` property
* * Everyone can see list of users
* * Everyone can see user by ID
* * Email entity
* * Mostly email only can be access/modify/deleted by the owner of the data
*
* so here we need to define the logic of the Owner of User and Entity
*/
/**
* First we define the owner of the data of User entity.
* Owner Definition: when the current login user match the entity ID
*/
entityPolicy(User)
// the first parameter is ctx, we destruct only to get the current login user claims
// the second parameter is the current ID of entity (User entity)
.register("Owner", ({ user }, id) => user?.userId === id)
/**
* Next we define the owner of the data of Email entity
* Owner Definition: when the current login user match the Email.user.id
*/
entityPolicy(Email)
.register("Owner", async ({ user }, id) => {
const repo = getRepository(Email)
// get the email by ID and populate the user property
const email = await repo.findOne(id, { relations: ["user"] })
// compare if the current login user id is the same with email user id
return user?.userId === email?.user.id
})
|
plumier/examples
|
02-controller/routing/src/controller/04-nested-restful-controller.ts
|
<filename>02-controller/routing/src/controller/04-nested-restful-controller.ts<gh_stars>1-10
import { meta, route } from "plumier"
/**
* With combination of root route, we can make a nested restful routes
*/
export class Log {
@meta.property()
message:string
}
@route.root("user/:uid/logs")
export class UsersLogsController {
// POST /users/:uid/logs
@route.post("")
save(uid:string, data:Log){
return {}
}
// GET /users/:uid/logs
@route.get("")
list(uid:string, limit:number, offset:number){
return {}
}
// GET /users/:uid/logs/:id
@route.get(":id")
get(uid:string, id:string){
return {}
}
// PUT /users/:uid/logs/:id
@route.put(":id")
replace(uid:string, id:string){
return {}
}
// PATCH /users/:uid/logs/:id
@route.patch(":id")
modify(uid:string, id:string){
return {}
}
// DELETE /users/:uid/logs/:id
@route.delete(":id")
delete(uid:string, id:string){
return {}
}
}
|
plumier/examples
|
04-first-class-entity/generic-controller-typeorm/src/controller/users-controller.ts
|
import { GenericController } from "@plumier/typeorm"
import { User } from "../entity/users-entity"
// create generic controller using entity
// it will serve /users
export class UsersController extends GenericController(User){}
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/carts/carts-policy.ts
|
<filename>08-complete-example/marketplace-api/src/api/carts/carts-policy.ts
import { entityPolicy } from "plumier"
import { getRepository } from "typeorm"
import { Cart } from "./carts-entity"
entityPolicy(Cart).register("ResourceOwner", async ({ user }, id) => {
const cart = await getRepository(Cart)
.findOne(id, { relations: ["user"], cache: true })
return cart?.state === "Open" && cart?.user.id === user?.userId && !cart.deleted
})
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/shops/shops-entity.ts
|
<gh_stars>1-10
import { noop } from "@plumier/reflect"
import { api, authorize, bind, ControllerBuilder, genericController, JwtClaims, meta, preSave, val } from "plumier"
import { Column, Entity, getRepository, OneToMany } from "typeorm"
import { EntityBase } from "../../_shared/entity-base"
import { Order } from "../orders/order-entity"
import { Product } from "../products/products-entity"
import { ShopUser } from "../shops-users/shops-users-entity"
// /api/shops
@genericController(c => {
c.methods("Delete", "Put", "Patch").authorize("ShopOwner")
})
@api.tag("Shop Management")
@Entity()
export class Shop extends EntityBase {
@val.required()
@Column()
name: string
// /api/shops/{pid}/users
@genericController(c => {
c.mutators().authorize("ShopOwner")
c.accessors().authorize("ShopOwner", "ShopStaff")
.transformer(ShopUserDto, transformer)
})
@api.tag("Shop User Management")
@authorize.none()
@OneToMany(x => ShopUser, x => x.shop)
users: ShopUser[]
// /api/shops/{pid}/products
@genericController(c => {
c.mutators().authorize("ShopOwner", "ShopStaff")
})
@api.tag("Shop Product Management")
@authorize.none()
@OneToMany(x => Product, x => x.shop)
products: Product[]
// /api/shops/{pid}/orders
@genericController(c => {
c.mutators().ignore()
c.accessors().authorize("ShopOwner", "ShopStaff")
})
@api.tag("Shop Order Management")
@authorize.none()
@OneToMany(x => Order, x => x.shop)
orders: Order[]
@preSave("post")
async setShopOwner(@bind.user() user: JwtClaims) {
const owner = await getRepository(ShopUser)
.save({ user: { id: user.userId }, role: "ShopOwner" })
this.users = [owner]
}
}
const transformer = (x: ShopUser) => ({
userId: x.user.id,
name: x.user.name,
role: x.role
})
export class ShopUserDto {
@meta.property()
userId: number
@meta.property()
name: string
@meta.property()
role: "ShopOwner" | "ShopStaff"
}
|
plumier/examples
|
02-controller/type-conversion/src/controller/users-controller.ts
|
import { meta, route, val } from "plumier"
export class User {
/**
* Property need to have at least one decorator for type conversion to work
* use @meta.property() for that
*/
@meta.property()
email: string
@meta.property()
name: string
/**
* Data type array need to specified explicitly
*/
@meta.type(x => [String])
emails: string[]
}
export class UsersController {
/**
* Request body will be checked match with User data type,
* if provided property value with different data type,
* will returned http status 422 with proper error message
*/
@route.post("")
save(data: User) {
return {}
}
/**
* query parameter receive input match with its data type
* Valid query
* /users/get?num=123
* /users/get?str=lorem+ipsum
* /users/get?bo=true (true, false, yes, no, 1, 0, on, off)
* /users/get?dt=2021-1-1 or use ISO 8601
*/
@route.get()
get(num:number, str:string, bo:boolean, dt:Date){
return {}
}
}
|
plumier/examples
|
05-security/basic-security/src/controller/auth-controller.ts
|
<reponame>plumier/examples<gh_stars>1-10
import { sign } from "jsonwebtoken"
import { authorize, HttpStatusError, JwtClaims, route } from "plumier"
/**
* JwtClaims is the data structure of user claims of JWT token used in ctx.user
* Augment the JwtClaims, adding properties required, so those properties accessible on ctx.user
*/
declare module "plumier" {
interface JwtClaims {
userId: number,
role: "Admin" | "SuperAdmin" | "User"
}
}
export class AuthController {
// Public is builtin auth policy to make route accessible by unauthenticated user
@authorize.route("Public")
@route.post()
login(username: string, password: string) {
if (username !== "demo" || password !== "<PASSWORD>")
throw new HttpStatusError(402, "Invalid username or password")
// if login pass, sign the user claims match with the JwtClaims structure
// API consumer then should use this token for each request as Bearer
const token = sign(<JwtClaims>{ userId: 1234, role: "User" }, process.env.PLUM_JWT_SECRET!)
return { token }
}
}
|
plumier/examples
|
03-data-access/data-access-mongoose/src/entity/users-entity.ts
|
<filename>03-data-access/data-access-mongoose/src/entity/users-entity.ts
import { collection } from "@plumier/mongoose"
import { EntityBase } from "./base-entity"
@collection()
export class User extends EntityBase {
@collection.property()
email: string
@collection.property()
name: string
}
|
plumier/examples
|
08-complete-example/marketplace-api/test/products.spec.ts
|
import supertest from "supertest"
import createApp from "../src/app"
import { createShop, createUser, ignore } from "./_helper"
describe("Products", () => {
it("Should able to list all items globally", async () => {
const app = await createApp({ mode: "production" })
await createShop(app, {
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2500 },
{ name: "Li-Ion Battery", basePrice: 200, price: 250 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 900 },
]
})
await createShop(app, {
shop: { name: "Ali Shop" },
owner: { email: "<EMAIL>" },
staffs: [],
items: [
{ name: "MacBook Pro 16 2020", basePrice: 2000, price: 2100 },
{ name: "Li-Ion Battery", basePrice: 200, price: 210 },
{ name: "M3 SSD 1TB", basePrice: 700, price: 800 },
]
})
const user = await createUser(app, { email: "<EMAIL>", name: "<NAME>" })
const { body } = await supertest(app.callback())
.get("/api/products")
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(body.length).toBe(6)
expect(body[0]).toMatchSnapshot({ ...ignore, shop: { ...ignore } })
})
})
|
plumier/examples
|
03-data-access/data-access-typeorm/src/index.ts
|
<filename>03-data-access/data-access-typeorm/src/index.ts<gh_stars>1-10
import { TypeORMFacility } from "@plumier/typeorm"
import Plumier, { WebApiFacility } from "plumier"
new Plumier()
.set(new WebApiFacility())
// install TypeORMFacility, it normalize TypeORM entities
// to make Plumier reflection library able to introspect them.
// put connection string on environment variable or .env file like .env-example file
.set(new TypeORMFacility())
.listen(8000)
|
plumier/examples
|
08-complete-example/marketplace-api/test/images.spec.ts
|
import { join } from "path"
import supertest from "supertest"
import createApp from "../src/app"
import { createUser } from "./_helper"
describe("Shops Images", () => {
it("Should upload file properly", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const { body: img } = await supertest(app.callback())
.post(`/api/images/upload`)
.attach("file", join(__dirname, "image/landscape.jpeg"))
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(img).toMatchSnapshot()
})
})
|
plumier/examples
|
02-controller/parameter-binding/src/controller/binding-controller.ts
|
import { Context } from "koa"
import { bind, JwtClaims, meta, route } from "plumier"
/**
* Example model
* each property required to be decorated
* to make reflection library able to get its data type
*/
class Body {
@meta.property()
string: string
@meta.property()
number: number
@meta.property()
date: Date
@meta.property()
boolean: boolean
}
export class BindingsController {
/**
* Name Binding
* bind request query into action parameters match its name
*
* Example request:
* GET /bindings/byname?page=1&limit=2&name=hello
*/
@route.get()
byName(page: number, limit: number, name: string) {
return {}
}
/**
* Model Binding
* bind request body with action parameter which has datatype of type custom class (model)
* model binding usually used with http method POST, PUT, PATCH
*
* Example request:
* POST /bindings/bymodel
* body: { string: "lorem", number: 123, date: "2021-1-1", date: false }
*/
@route.post()
byModel(body: Body) {
return {}
}
/**
* Decorator Binding
* bind request part with action parameter
*
* Example request
* GET /bindings/bydecorator
* Header: Authentication=Bearer <token>
*/
@route.get()
byDecorator(@bind.user() user: JwtClaims, @bind.ctx() ctx: Context) {
return {}
}
/**
* Decorator Binding (with model)
* Decorator binding can be bound with action parameter of data type custom class
*
* Example request
* GET /bindings/bydecoratormodel?string=lorem&number=123&boolean=false&date=2021-1-1
*/
@route.get()
byDecoratorModel(@bind.query() query:Body) {
return {}
}
/**
* Mix Binding
* Parameter binding can be mixed in single action
*
* Example request
* POST /bindings/bymix?string=lorem&number=123
* Header: Authentication=Bearer <token>
* body: { string: "lorem", number: 123, date: "2021-1-1", date: false }
*/
@route.post()
byMix(string:string, number:number, body:Body, @bind.user() user:JwtClaims){
return {}
}
}
|
plumier/examples
|
06-swagger/swagger/src/index.ts
|
<reponame>plumier/examples<filename>06-swagger/swagger/src/index.ts
import { SwaggerFacility } from "@plumier/swagger"
import { TypeORMFacility } from "@plumier/typeorm"
import Plumier, { WebApiFacility } from "plumier"
new Plumier()
.set(new WebApiFacility())
.set(new TypeORMFacility())
.set(new SwaggerFacility({
// add project information (optional)
info: {
title: "My Cool Project",
version: "1.0.0",
description: "Lorem ipsum dolor sit amet lorem ipsum dolor sit amet"
}
}))
.listen(8000)
|
plumier/examples
|
08-complete-example/marketplace-api/src/api/users/users-policy.ts
|
<reponame>plumier/examples
import { entityPolicy } from "plumier"
import { User } from "./users-entity"
entityPolicy(User)
.register("ResourceOwner", (ctx, id) => ctx.user?.userId === id)
|
plumier/examples
|
08-complete-example/marketplace-api/test/carts.spec.ts
|
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createCart, createUser, ignore } from "./_helper"
afterEach(async () => {
await closeConnection()
})
describe("Carts", () => {
it("Should create new chart when no open cart", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const { body } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(body).toMatchSnapshot()
})
it("Should create different chart with different user", async () => {
const app = await createApp({ mode: "production" })
const ali = await createUser(app)
const ula = await createUser(app, { email: "<EMAIL>" })
const { body: aliCart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${ali.token}`)
.expect(200)
const { body: ulaCart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${ula.token}`)
.expect(200)
expect(aliCart.id !== ulaCart.id).toBe(true)
})
it("Should not create a new cart when already opened one", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const { body: first } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: second } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(first.id === second.id).toBe(true)
})
it("Should able to assign shipping address", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const { body: shipping } = await supertest(app.callback())
.post(`/api/users/${user.id}/shipping-addresses`)
.send({
address: "Br. Guntur Kemenuh Blahbatuh Gianyar",
city: "Gianyar",
country: "Indonesia",
zipCode: "80281",
})
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body: cart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.patch(`/api/carts/${cart.id}`)
.send({ address: shipping.id })
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
const { body } = await supertest(app.callback())
.get(`/api/carts/${cart.id}`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
expect(body).toMatchSnapshot({ ...ignore, address: ignore, user: ignore })
})
it("Should not able to set by other user", async () => {
const app = await createApp({ mode: "production" })
const user = await createUser(app)
const otherUser = await createUser(app, { email: "<EMAIL>" })
const { body: shipping } = await supertest(app.callback())
.post(`/api/users/${otherUser.id}/shipping-addresses`)
.send({
address: "Br. Guntur Kemenuh Blahbatuh Gianyar",
city: "Gianyar",
country: "Indonesia",
zipCode: "80281",
})
.set("Authorization", `Bearer ${otherUser.token}`)
.expect(200)
const { body: cart } = await supertest(app.callback())
.get(`/api/carts/open`)
.set("Authorization", `Bearer ${user.token}`)
.expect(200)
await supertest(app.callback())
.patch(`/api/carts/${cart.id}`)
.send({ address: shipping.id })
.set("Authorization", `Bearer ${otherUser.token}`)
.expect(403)
})
it("Should checkout cart properly", async () => {
const app = await createApp({ mode: "production" })
const cart = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${cart.user.token}`)
.expect(200)
const { body: orders } = await supertest(app.callback())
.get(`/api/users/${cart.user.id}/orders`)
.set("Authorization", `Bearer ${cart.user.token}`)
.expect(200)
expect(orders.map((x: any) => ({ shop: x.shop.name, state: x.state }))).toMatchSnapshot()
})
it("Should not able to access checked cart", async () => {
const app = await createApp({ mode: "production" })
const cart = await createCart(app)
await supertest(app.callback())
.post("/api/carts/checkout")
.set("Authorization", `Bearer ${cart.user.token}`)
.expect(200)
await supertest(app.callback())
.get(`/api/carts/${cart.id}`)
.set("Authorization", `Bearer ${cart.user.token}`)
.expect(403)
})
})
|
plumier/examples
|
08-complete-example/marketplace-api/test/auth.spec.ts
|
<reponame>plumier/examples
import decode from "jwt-decode"
import supertest from "supertest"
import createApp from "../src/app"
import { closeConnection, createUser } from "./_helper"
afterEach(async () => {
await closeConnection()
})
const tokenIgnore = { iat: expect.any(Number), exp: expect.any(Number) }
describe("Authorization", () => {
it("Should able to login properly", async () => {
const app = await createApp({ mode: "production" })
const user = { email: "<EMAIL>", password: "<PASSWORD>" }
await createUser(app, user)
const { body: tokens } = await supertest(app.callback())
.post("/api/auth/login")
.send(user)
.expect(200)
expect(decode(tokens.token)).toMatchSnapshot(tokenIgnore)
expect(decode(tokens.refreshToken)).toMatchSnapshot(tokenIgnore)
})
it("Should able to request refresh token with refresh token", async () => {
const app = await createApp({ mode: "production" })
const user = { email: "<EMAIL>", password: "<PASSWORD>" }
await createUser(app, user)
const { body: tokens } = await supertest(app.callback())
.post("/api/auth/login")
.send(user)
.expect(200)
const { body: secondTokens } = await supertest(app.callback())
.post("/api/auth/refresh")
.set("Authorization", `Bearer ${tokens.refreshToken}`)
.expect(200)
expect(decode(secondTokens.token)).toMatchSnapshot(tokenIgnore)
expect(decode(secondTokens.refreshToken)).toMatchSnapshot(tokenIgnore)
})
it("Should not able to request refresh token with token", async () => {
const app = await createApp({ mode: "production" })
const user = { email: "<EMAIL>", password: "<PASSWORD>" }
await createUser(app, user)
const { body: tokens } = await supertest(app.callback())
.post("/api/auth/login")
.send(user)
.expect(200)
await supertest(app.callback())
.post("/api/auth/refresh")
.set("Authorization", `Bearer ${tokens.token}`)
.expect(403)
})
it("Should able to access private route using token", async () => {
const app = await createApp({ mode: "production" })
const user = { email: "<EMAIL>", password: "<PASSWORD>" }
await createUser(app, user)
const { body: tokens } = await supertest(app.callback())
.post("/api/auth/login")
.send(user)
.expect(200)
await supertest(app.callback())
.post("/api/auth/logout")
.set("Authorization", `Bearer ${tokens.token}`)
.expect(200)
})
it("Should not able to access private route using refresh token", async () => {
const app = await createApp({ mode: "production" })
const user = { email: "<EMAIL>", password: "<PASSWORD>" }
await createUser(app, user)
const { body: tokens } = await supertest(app.callback())
.post("/api/auth/login")
.send(user)
.expect(200)
await supertest(app.callback())
.post("/api/auth/logout")
.set("Authorization", `Bearer ${tokens.refreshToken}`)
.expect(403)
})
})
|
plumier/examples
|
01-project-layout/file-layout-modular/src/api/users/users-entity.ts
|
import { meta } from "plumier"
export class User {
@meta.property()
userName:string
@meta.property()
name:string
}
|
plumier/examples
|
07-serve-static-and-file-upload/file-upload-s3/src/controller/file-controller.ts
|
import { FormFile, meta, route, val } from "plumier"
import { join } from "path"
import sdk from "aws-sdk"
import { readFile } from "fs"
import { promisify } from "util"
const readFileAsync = promisify(readFile)
const s3 = new sdk.S3({
accessKeyId: process.env.AWS_ACCESS_ID,
secretAccessKey: process.env.AWS_ACCESS_KEY,
});
export class FileController {
/**
* Create upload handler POST /file/upload
* receive multipart form with <input type="file" name="file"/>
* which maximum uploaded file is 3MB
*/
@route.post()
async upload(@val.file("3MB") file: FormFile) {
// copy the uploaded file from temp directory into files directory
const buf = await readFileAsync(file.path)
const result = await s3.upload({
Bucket: <string>process.env.AWS_BUCKET_NAME,
Body: buf,
Key: file.name,
ACL: "public-read",
}).promise()
return { url: result.Location }
}
/**
* Create upload handler for multiple file upload POST /file/multiple
* receive multipart form with <input type="file" name="file" multiple/>
* which maximum of each uploaded file is 3MB
*/
@route.post()
async multiple(@val.file("3MB") @meta.type([FormFile]) file: FormFile[]) {
// copy the uploaded files from temp directory into files directory
const result = []
for (const f of file) {
const buf = await readFileAsync(f.path)
const res = await s3.upload({
Bucket: <string>process.env.AWS_BUCKET_NAME,
Body: buf,
Key: f.name,
ACL: "public-read",
}).promise()
result.push({ url: res.Location })
}
return result
}
}
|
capitalch/next
|
xprofile-test/code-block.tsx
|
import React from "react";
// import PropTypes from "prop-types";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { duotoneDark } from "react-syntax-highlighter/dist/cjs/styles/prism";
// class CodeBlock extends PureComponent {
// static propTypes = {
// value: PropTypes.string.isRequired,
// language: PropTypes.string
// };
// static defaultProps = {
// language: null
// };
// render() {
// let { language, value } = this.props;
// language = 'javascript';
// return (
// <SyntaxHighlighter language={language} style={xonokai}>
// {value}
// </SyntaxHighlighter>
// );
// }
// }
function CodeBlock({value, language}) {
return <SyntaxHighlighter language={language} style={duotoneDark}>
{value}
</SyntaxHighlighter>
}
export default CodeBlock;
|
capitalch/next
|
adam4/components/contact.tsx
|
<filename>adam4/components/contact.tsx<gh_stars>0
import React, { useState } from 'react'
import styled from 'styled-components'
import axios from 'axios'
import settings from '../settings.json'
function Contact() {
const [name, setName] = useState('');
const [mobile, setMobile] = useState('');
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
return (
<div>
<AddressDetails>
<h3>Contact details of Sushant Agrawal</h3>
<div> {contactDetails.address1}</div>
<div>{contactDetails.address2}</div>
<div>{contactDetails.nearLocation}</div>
<div>{contactDetails.district}</div>
<div>{contactDetails.pin}</div>
<div>{contactDetails.phone}</div>
<div>{contactDetails.email}</div>
</AddressDetails>
<h4>Directly mail to Sushant</h4>
<div>
<Form onSubmit={sendEmail}>
<div>
<label>
Your name: <span className='required'>*</span>
</label>
</div>
<div>
<input
type="text"
required
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<br></br>
<div>
<label>Your mobile: <span className='required'>*</span></label>
</div>
<div>
<input type="text" pattern="[0-9]*" required name="mobile" value={mobile} minLength={10} maxLength={10} onChange={e => setMobile(e.target.value)} />
</div>
<br></br>
<div>
<label>Your email: <span className='required'>*</span></label>
</div>
<div>
<input type="email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" name="email" value={email} onChange={e => setEmail(e.target.value)} />
</div>
<br></br>
<div>
<label>Message: <span className='required'>*</span></label>
</div>
<div>
<textarea required rows={6} name="message" value={message} onChange={e => setMessage(e.target.value)}></textarea>
</div>
<br></br>
<div>
<button type="submit" className="mailButton">Submit</button>
</div>
<div className='notes'> Fields marked with <span className='required'>*</span> are required</div>
</Form>
</div>
</div>
);
function sendEmail(evt:any) {
evt.preventDefault();
const data = {
subject: `Message from Sushant Agrawal's profile`,
text: `From: ${email},\r\nName: ${name}\r\nMobile: ${mobile}\r\nMessage: ${message}`
};
axios.post(settings.emailHost, data)
.then(() => resetForm())
.catch(
err => {
console.log(err);
}
);
}
function resetForm() {
setName("");
setMobile("");
setEmail("");
setMessage("");
}
}
const AddressDetails = styled.div`
margin-top: 0.5em;
width:100%;
`;
const Form = styled.form`
.required {
color: red;
}
input{
width: 100%;
font-size:1rem;
line-height: 1.3rem;
}
textarea{
width:100%;
font-size:1rem;
}
.notes{
font-size:0.9rem;
}
`;
const contactDetails = {
address1: '92/2A Bidhan Nagar Road',
address2: '1st floor, Concord towers',
nearLocation: 'Near Ultadanga More',
district: 'Kolkata, West bengal, India',
pin: 'Pin: 700067',
phone: 'Mobile: +91 8910 322267',
email: 'Email: <EMAIL>'
};
export default Contact;
|
capitalch/next
|
xprofile/components/blogs.tsx
|
<filename>xprofile/components/blogs.tsx
import React from 'react'
import Link from 'next/link'
import styled from 'styled-components'
import moment from 'moment'
function Blogs({ blogs }) {
return <div>
<h3>Blogs by Sushant</h3>
{Object.keys(blogs).map((cat, index) => {
return <div key={index}>
<Styledcat style={{ textTransform: 'capitalize' }}>{cat}</Styledcat>
{
blogs[cat].sort((b: any, a: any): any => (a.createdOn.valueOf() - b.createdOn.valueOf())).map((obj, index) => {
const content = obj.content.replace(/[\[\]#]+/g, ''); //remove all occurance of '#'
return <StyledDiv key={index}>
<Link href={`/blog/${obj.slug}`}><a>{`${obj.title}: `}</a></Link>
<StyledDate>{`${moment(obj.createdOn).format('YYYY, Do MMM')}`}</StyledDate>
<br></br>
<StyledShortContent>{content +'...'}</StyledShortContent>
<Link href={`/blog/${obj.slug}`}>
<a>{' '}Read more... </a>
</Link>
</StyledDiv>
})}
</div>
})}
</div>
}
const StyledDiv = styled.div`
line-height: 1.5rem;
font-size: 1rem;
margin-left: 1rem;
/* margin-top: 1rem; */
a {
font-weight: bold;
color: blue;
display: inline;
text-decoration: none;
:active {
color: red;
}
:hover {
color: red;
}
}
`
const Styledcat = styled.div`
color:black;
margin:0;
font-weight:bold;
`
const StyledDate = styled.span`
color:darkorange;
`
const StyledShortContent = styled.span`
color:darkmagenta;
`
export default Blogs
|
capitalch/next
|
xprofile/utils.tsx
|
import React from 'react'
import axios from 'axios'
function axiosGet(url, params) {
return axios.get(url, { params: params })
}
export { axiosGet }
function getCommentsArray(pageComments) {
const outArray: any[] = []
function process(arr: any[], level: number) {
arr.forEach(x => {
outArray.push({ level: level, ...x })
x.children && (x.children.length > 0) && process(x.children, level + 1)
})
}
process(pageComments, 0)
return outArray
}
export { getCommentsArray }
/*
// try {
// const ret = await axios.get(url, { params: params })
// setArr(getCommentsArray(ret.data))
// } catch (e) {
// console.log((e.response && e.response.data.message) || e.message)
// }
*/
|
capitalch/next
|
adam4/components/layout.tsx
|
<reponame>capitalch/next<filename>adam4/components/layout.tsx
import React from 'react';
import styled from 'styled-components';
import Header from './header';
import Footer from './footer'
// import ReactMarkdown from 'react-markdown/with-html';
function Layout({ currentPage = '', content = '', children = '' , isBanner=false}) {
return (
<StyledLayout>
<Header currentPage={currentPage}>Home</Header>
{isBanner && <StyledBanner src="/static/images/banner1.jpg" alt="banner image"></StyledBanner>}
<StyledLeft>
<ProfileImage src="/static/images/sushant2.jpg" alt='Image of Sushant Agrawal' />
<ProfileText>
<NAME>
<StyledH5>Full stack software developer</StyledH5>
</ProfileText>
</StyledLeft>
<StyledRight></StyledRight>
<XMain content={content} children={children}></XMain>
</StyledLayout>
);
}
function XMain({ content, children }:any) {
let ret;
if (content && children) {
ret = <StyledMain>
{/* <ReactMarkdown escapeHtml={false} source={content} /> */}
<StyledMain>{children}</StyledMain>
<Footer></Footer>
</StyledMain>
} else {
ret = <StyledMain>{children}<Footer></Footer></StyledMain>
}
return ret
}
const StyledLayout = styled.div`
display: grid;
min-height:calc(100vh - 3px);
@media(max-width: 500px){
grid-template-areas:'header' 'main' 'left';
grid-auto-rows: min-content auto auto;
}
@media only screen and (min-width: 501px) and (max-width: 992px) {
grid-template-areas: 'header header' 'banner banner' 'main right' 'left right';
grid-auto-rows: min-content 100px auto auto;
grid-template-columns: auto minmax(10%,20%);
}
@media only screen and (min-width: 993px) and (max-width: 1200px) {
grid-template-areas: 'header header header' 'banner banner banner' 'left main right';
grid-template-columns: 16% auto 25%;
grid-template-rows: 58px 200px auto;
}
@media only screen and (min-width: 1201px) and (max-width: 1500px){
grid-template-areas: 'header header header' 'banner banner banner' 'left main right';
grid-template-columns: 16% auto 30%;
grid-template-rows: 58px minmax(0,200px) auto;
}
@media only screen and (min-width: 1501px) {
grid-template-areas: 'header header header' 'banner banner banner' 'left main right';
grid-template-columns: 16% auto 43%;
grid-template-rows: 58px min-content auto;
}
`
const StyledBanner = styled.img`
grid-area: banner;
width:100%;
@media(max-width: 500px){
display:none;
}
`
const StyledRight = styled.div`
grid-area: right;
background-color: #fff;;
@media(max-width: 992px){
display:none;
}
`
const StyledMain = styled.div`
grid-area: main;
background-color:#fff;
line-height: 2rem;
font-size: 1.2rem;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', 'sans-serif';
margin-left:2rem;
margin-right:2.3rem;
text-align: justify;
`
const ProfileImage = styled.img`
display:block;
margin:auto;
padding-top: 2rem;
`
const ProfileText = styled.div`
text-align:center;
`
const StyledLeft = styled.div`
grid-area: left;
background-color: #fff;
`
const StyledH5 = styled.h5`
color: maroon;
font-size: 0.8rem;
margin: 0;
`
export default Layout;
/*
*/
|
capitalch/next
|
adam4/pages/index.tsx
|
import React from "react";
import Head from "../components/head";
import Layout from "../components/layout";
import GlobalStyle from "../handy/globalStyle";
import Contact from "../components/contact";
import Skillset from "../components/skillset";
import axios from "axios";
import settings from "../settings.json";
import Comments from "../components/comments";
const slugMapping: any = {
home: "Contact S<NAME> for React.js development",
about: "About node.js development by <NAME>",
contact: "Contact <NAME> for Flutter development",
resume: "Resume of <NAME>, full stack software developer",
skillset: "Skills of full stack software consultant Sushant Agrawal",
academics: "Academics of full stack software consultant Sushant Agrawal",
projects: "Projects done by S<NAME>, full stack software developer",
qa: "Interview of full stack software consultant Sushant Agrawal",
};
const IndexPage = ({ content, slug, pageComments, skills }: any) => {
return (
<div>
<GlobalStyle />
<Head title={slugMapping[slug]} />
{getPageContent({ content, slug, pageComments, skills })}
</div>
);
};
IndexPage.getInitialProps = async ({ res, asPath }: any) => {
let slug = asPath.slice(1) || "home"; // remove first char (/) from asPath
!allPages[slug] && (slug = "home");
let content;
allPages[slug].isMDFile &&
(content = (await import(`../docs/pages/${slug}.md`)).default);
let skills = {};
if (res) {
if (slug === "skillset") {
skills = JSON.parse(res.locals.skills);
}
} else {
if (slug === "skillset") {
const d = (await axios.get("/skillset?client=true")).data;
skills = JSON.parse(d.skills);
}
}
const url = `${settings.commentsUrl}/${slug}`;
const params = {
token: settings.token,
};
let pageComments;
try {
pageComments = (
await axios.get(url, {
params: params,
})
).data;
} catch (e: any) {
console.log((e.response && e.response.data.message) || e.message);
}
return {
content,
slug,
pageComments,
skills,
};
};
function getPageContent({ content, slug, pageComments, skills }:any):any {
let Ret;
if (allPages[slug].isMDFile) {
Ret = (
<></>
// <Layout
// isBanner={allPages[slug].isBanner}
// currentPage={slug}
// content={content}>
// <Comments pageComments={pageComments} slug={slug}></Comments>
// </Layout>
);
} else {
Ret = (
<div>Placeholder</div>
// <Layout isBanner={allPages[slug].isBanner} currentPage={slug} >
// {allPages[slug].component(skills)}{" "}
// <Comments pageComments={pageComments} slug={slug}></Comments>
// </Layout>
);
}
return Ret;
}
const allPages: any = {
home: { isBanner: true, isMDFile: true },
about: { isBanner: true, isMDFile: true },
contact: {
isBanner: true,
isMDFile: false,
component: () => <Contact></Contact>,
},
resume: { isBanner: false, isMDFile: true },
skillset: {
isBanner: false,
isMDFile: false,
component: (skills: any) => <Skillset skills={skills}></Skillset>,
},
academics: { isBanner: false, isMDFile: true },
projects: { isBanner: false, isMDFile: true },
qa: { isBanner: false, isMDFile: true }, //,
};
export default IndexPage;
/*
*/
|
capitalch/next
|
xprofile-test/pages/blogs.tsx
|
import React from 'react';
import GlobalStyle from '../handy/globalStyle';
import axios from 'axios';
import Head from '../components/head';
import Blogs from '../components/blogs';
import Layout from '../components/layout';
function BlogsPage({ blogs, slug }) {
return (
<div>
<GlobalStyle />
<Head title='Blogs' />
<Layout currentPage={slug}><Blogs blogs={blogs}></Blogs></Layout>
</div>
);
}
BlogsPage.getInitialProps = async ({ req, res }) => {
try {
const isServer = !!req;
let blogs;
if (isServer) {
blogs = res.locals.blogs;
} else {
const d = await axios.get('/blogs?client=true');
blogs = d.data;
}
const slug = 'blogs'
return { blogs, slug };
} catch (e) {
console.log(e);
}
};
export default BlogsPage;
|
capitalch/next
|
sush-blogs2/store.tsx
|
<filename>sush-blogs2/store.tsx
const cache = {};
const store: any = {};
store.setCache = (key, value) => {
cache[key] = value;
};
store.getCache = (key) => cache[key];
export { store };
|
capitalch/next
|
xprofile-test/components/footer.tsx
|
import React, { useState, useEffect } from 'react'
import styled from 'styled-components'
import axios from 'axios'
import settings from '../settings.json'
function Footer() {
let [hitCount, setHitCount] = useState(0);
useEffect(() => {
axios.get(settings.hitCountUrl).then((res)=>{
hitCount = res.data.hits
setHitCount(hitCount)
})
}, [])
return <StyledFooter>Hits:{hitCount}</StyledFooter>
}
const StyledFooter = styled.div`
font-size: 0.8rem;
text-align:right;
`
export default Footer
/*
; (async () => {
const res = await axios.get(settings.hitCountUrl)
hitCount = res.data.hits
setHitCount(hitCount)
})()
*/
|
capitalch/next
|
xprofile-test/handy/globalStyle.tsx
|
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle`
body {
margin:1px;
}
* {
box-sizing: border-box;
}
`
export default GlobalStyle
|
capitalch/next
|
xprofile-test/pages/blog.tsx
|
<filename>xprofile-test/pages/blog.tsx
import React from 'react'
import Link from 'next/link'
import styled from 'styled-components'
import GlobalStyle from '../handy/globalStyle'
import Layout from '../components/layout'
import Head from '../components/head'
import CodeBlock from '../code-block'
import Comments from '../components/comments'
import axios from 'axios'
import ReactMarkdown from 'react-markdown'
import settings from '../settings.json'
// import Prism from 'prismjs';
// import './prism.scss'
// import showdown from 'showdown'
function BlogPage({ content, title, pageComments, slug }) {
return (
<div>
<GlobalStyle />
<Head title='Blog' />
<Layout>
<StyledLink><Link href='/blogs'><a>Back to blogs</a></Link></StyledLink>
<h3>{title}</h3>
<ReactMarkdown escapeHtml={false} source={content} renderers={{ code: CodeBlock }}>
</ReactMarkdown>
<Comments pageComments={pageComments} slug={slug}></Comments>
</Layout>
</div>
);
}
BlogPage.getInitialProps = async ({ res, asPath }) => {
try {
const content = res.locals.content
const title = res.locals.title
const slug = asPath.split('/')[2];
// return { content, title}
const url = `${settings.commentsUrl}/projects`
const params = {
token: settings.token
}
const pageComments = (await axios.get(url, {
params: params
})).data
return {
content
, title
, pageComments
, slug
};
} catch (e) {
console.log((e.response && e.response.data.message) || e.message)
}
}
const StyledLink = styled.div`
margin-top:1rem;
`
export default BlogPage
/*
<div dangerouslySetInnerHTML={{ __html: content }} />
const slug = asPath.split('/')[2];
const converter = new showdown.Converter(
{
metadata: true //, // extensions: [showdownHighlight]
}
);
const md = (await require(`../docs/blogs/${slug}.md`)).default;
const content = converter.makeHtml(md);
const meta = converter.getMetadata();
const url = `${settings.commentsUrl}/projects`
const params = {
token: settings.token
}
const pageComments = (await axios.get(url, {
params: params
})).data
return {
content
, meta
, pageComments
, md
};
*/
|
capitalch/next
|
xprofile-test/components/blogs.tsx
|
import React from 'react'
import Link from 'next/link'
import styled from 'styled-components'
function Blogs({ blogs }) {
return <div>
<h3>Blogs by Sushant</h3>
{Object.keys(blogs).map((cat, index) => {
return <div key={index}>
<Styledcat style={{ textTransform: 'capitalize' }}>{cat}</Styledcat>
{blogs[cat].map((obj, index) => {
return <StyledDiv key={index}>
{/* <StyledAnchor href={`/blog/${obj.slug}`}>{obj.title}</StyledAnchor> */}
<Link href={`/blog/${obj.slug}`}><StyledAnchor>{obj.title}</StyledAnchor></Link>
</StyledDiv>
})}
</div>
})}
</div>
}
const StyledDiv = styled.div`
line-height:1.5rem;
`
const Styledcat = styled.div`
color:darkslategrey;
font-weight:bold;
`
const StyledAnchor = styled.a`
font-size:1rem;
color:orange;
line-height:1rem;
text-decoration:none;
font-weight:700;
cursor:pointer;
:visited {
color: grey;
}
:active {
color: red;
}
:hover {
color: blue;
}
`
export default Blogs
|
capitalch/next
|
xprofile-test/components/comments.tsx
|
import React, { useState, useEffect } from 'react'
import moment from 'moment'
import axios from 'axios'
import styled, { keyframes } from 'styled-components'
import { rollIn } from 'react-animations'
import settings from '../settings.json'
import diction from '../diction.json'
function Comments({ pageComments, slug }) {
const [arr, setArr] = useState([])
let [index, setIndex] = useState(-1)
useEffect(() => {
setArr(getCommentsArray(pageComments))
}, [])
return <div>
<StyledCommentButton onClick={() => { setRootForm() }}>{diction.comments.clickForNewComments}</StyledCommentButton>
<CommentsCount>Total {arr.length} comments</CommentsCount>
{arr.map((x, index) => {
const src = `/static/persons/${Math.floor(Math.random() * Math.floor(150))}.png`
if (x.id) {
return <StyledItem key={index} style={{ marginLeft: `${x.level * 4}rem` }}>
<div>
<StyledPerson src={src} alt='person'></StyledPerson>
<StyledName>
{x.mname}
</StyledName>
<StyledTime>{moment(x.commented_on).format('lll')}</StyledTime>
</div>
<div>{x.comment}</div>
<div><StyledCommentButton onClick={() => { setForm(x) }}>Reply</StyledCommentButton></div>
</StyledItem>
} else {
return <div key={index}>{x}</div>
}
})}
</div>
function setRootForm() {
if (index !== -1) {
arr.splice(index, 1)
}
index = 0
setIndex(index)
const parentId = null
arr.unshift(<SubmitForm startPos={0} props={{ index, setIndex, arr, setArr, slug, parentId }}></SubmitForm>)
setArr([...arr])
}
function setForm(arrayItem) {
if (index !== -1) {
arr.splice(index, 1)
}
const arrIndex = arr.findIndex((value) => value.id === arrayItem.id)
index = arrIndex + 1
setIndex(index)
const parentId = arrayItem.id
arr.splice(index, 0, <SubmitForm startPos={arrayItem.level} props={{ index, setIndex, arr, setArr, slug, parentId }}></SubmitForm>)
setArr([...arr]) //for refresh purpose ...arr is used
}
}
function getCommentsArray(pageComm) {
const outArray: any[] = []
function process(arr: any[], level: number) {
arr && (arr.length > 0) && arr.forEach(x => {
outArray.push({ level: level, ...x })
x.children && (x.children.length > 0) && process(x.children, level + 1)
})
}
process(pageComm, 0)
return outArray
}
function SubmitForm({ startPos, props }) {
const [comment, setComment] = useState('')
const [mname, setMname] = useState('')
const [email, setEmail] = useState('')
const [webSite, setWebSite] = useState('')
const [success, setSuccess] = useState(null)
const { index, setIndex, arr, setArr, slug, parentId } = props;
function newComment(e) {
e.preventDefault();
const payload = {
token: settings.token,
text: diction.newCommentId,
values:
{
parentId: parentId
, mname: mname
, email: email
, visitorSite: webSite
, comment: comment
}
}
axios.post(`${settings.commentsUrl}/${slug}`, payload)
.then(() => {
setSuccess(true)
setArr([...arr])
})
.catch(e => {
setSuccess(false);
console.log((e.response && e.response.data.message) || e.message)
setArr([...arr])
})
}
function cancelComment() {
if (index !== -1) {
arr.splice(index, 1) //delete at index
}
setIndex(-1)
setArr([...arr]) //refresh
}
const styledForm = <StyledForm onSubmit={newComment} style={{ marginLeft: `${startPos * 4 + 4}rem` }}>
<div>
<textarea
required
rows={6}
placeholder="Give comments"
name="comment"
value={comment}
onChange={(e) => setComment(e.target.value)}>
</textarea>
</div>
<div>
<input type='text'
required
placeholder='Your name'
name="mname"
value={mname}
onChange={e => setMname(e.target.value)}
></input>
</div>
<div>
<input
required
type='email'
pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
placeholder="Your email"
name="email"
value={email}
onChange={e => setEmail(e.target.value)}>
</input>
</div>
<div>
<input
type='text'
placeholder="Your web site"
name="webSite"
value={webSite}
onChange={e => setWebSite(e.target.value)}>
</input>
</div>
<div>
<button type="submit">Submit comments</button>
<button type="button" onClick={() => cancelComment()}>Cancel comments</button>
</div>
</StyledForm>
const successMessage = <StyledMessage> {diction.comments.submitted} </StyledMessage>
const failureMessage = <StyledMessage>{diction.comments.failure}</StyledMessage>
let ret;
if ((success === null) || (success === undefined)) {
ret = styledForm
} else if (success === false) {
ret = failureMessage
} else {
ret = successMessage
}
return ret
// return success ? successMessage : styledForm
}
const StyledPerson = styled.img`
height:15px;
width:15px;
margin-right:0.5rem;
margin-bottom:-0.1rem;
`
const CommentsCount = styled.span`
margin-left:1rem;
font-size: 1.0rem;
color:#990033;
`
const StyledMessage = styled.div`
background-color:#fff;
color: black;
font-size: 1.4rem;
font-weight: bold;
margin: 2rem 0;
padding:1rem;
background-color:#EEFECF;
font-style:italic;
border:1px solid red;
`
const StyledForm = styled.form`
animation:2s ${keyframes`${rollIn}`} ;
width:auto;
border: 1px solid grey;
/* margin: 1rem 0 2rem 0; */
margin-bottom:1.5rem;
margin-top:0.5rem;
input, textarea {
width:92%;
}
input {
height: 2rem;
margin: 0.5rem 1rem ;
}
textArea{
height: 6rem;
margin: 1rem 1rem 0.5rem 1rem;
}
button{
margin: 1rem 1rem ;
cursor:pointer;
}
`
const StyledName = styled.span`
color: #336600;
margin-right:0.5rem;
`
const StyledTime = styled.span`
font-size:0.9rem;
`
const StyledCommentButton = styled.button`
border: 0;
background: none;
box-shadow: none;
border-radius: 0px;
cursor:pointer;
margin: 0px;
padding: 0px;
color: blue;
:focus {
outline: none;
}
margin-bottom:1rem;
margin-top:1rem;
`
const StyledItem = styled.div`
display:flex;
flex-direction:column;
font-size: 1.0rem;
`
export default Comments
/*
*/
|
capitalch/next
|
xprofile-test/pages/index.tsx
|
<reponame>capitalch/next<gh_stars>0
import React, { useState, useEffect } from 'react'
import Head from '../components/head'
import Layout from '../components/layout'
import GlobalStyle from '../handy/globalStyle'
import Contact from '../components/contact'
import Skillset from '../components/skillset'
import axios from 'axios'
import settings from '../settings.json'
import Comments from '../components/comments'
const slugMapping = {
home: 'Home',
about: 'About Sushant',
contact: 'Contact details of Sushant',
resume: 'Resume of Sushant',
skillset: 'Skillsets of Sushant',
academics: 'Academics of Sushant',
projects: 'Projects done by Sushant',
qa: 'Questions and answers by Sushant',
}
//, pageComments
const IndexPage = ({ content, slug, pageComments }) => {
// let [pageComments, setPageComments] = useState([])
// useEffect(() => {
// console.log('useEffect')
// const url = `${settings.commentsUrl}/${slug}`
// const params = {
// token: settings.token
// }
// axios.get(url
// , {
// params: params
// }
// ).then(res => {
// console.log(res.data)
// setPageComments([...res.data])
// }).catch(e=>console.log(e))
// },[])
return (
<div>
<GlobalStyle />
<Head title={slugMapping[slug]} />
{getPageContent({ content, slug, pageComments })}
</div>
);
};
IndexPage.getInitialProps = async ({ asPath }) => {
let slug = asPath.slice(1) || 'home'; // remove first char (/) from asPath
(!allPages[slug]) && (slug = 'home');
let content;
(allPages[slug].isMDFile) && (content = (await import(`../docs/pages/${slug}.md`)).default)
const url = `${settings.commentsUrl}/${slug}`
const params = {
token: settings.token
}
let pageComments;
try {
pageComments = (await axios.get(url
, {
params: params
}
)).data
} catch (e) {
console.log((e.response && e.response.data.message) || e.message)
}
return {
content, slug
,
pageComments
};
};
function getPageContent({ content, slug, pageComments }) {
let Ret;
if (allPages[slug].isMDFile) {
Ret = <Layout isBanner={allPages[slug].isBanner} currentPage={slug} content={content}><Comments pageComments={pageComments} slug={slug}></Comments></Layout>;
} else {
Ret = <Layout isBanner={allPages[slug].isBanner} currentPage={slug}>{allPages[slug].component()} <Comments pageComments={pageComments} slug={slug}></Comments></Layout>;
}
return Ret;
}
const allPages = {
home: { isBanner: true, isMDFile: true },
about: { isBanner: true, isMDFile: true },
contact: { isBanner: true, isMDFile: false, component: () => <Contact></Contact> },
resume: { isBanner: false, isMDFile: true },
skillset: { isBanner: false, isMDFile: false, component: () => <Skillset></Skillset> },
academics: { isBanner: false, isMDFile: true },
projects: { isBanner: false, isMDFile: true },
qa: { isBanner: false, isMDFile: true }//,
// blogs: { isBanner: false, isMDFile: false, component: () => <Blogs></Blogs> }
}
export default IndexPage;
/*
*/
|
capitalch/next
|
adam4/components/skillset.tsx
|
<filename>adam4/components/skillset.tsx
import React, { Fragment } from 'react'
import styled from 'styled-components'
// import skills1 from '../docs/skills.json'
import diction from '../diction.json'
const Skillset = ({ skills }:any) => {
let runningIndex = 0;
function Skill({ allSkills, skillGroup }:any) {
return allSkills[skillGroup].map((skill:any, index:number) => {
runningIndex++;
return (
<tr key={index}>
<td>{runningIndex}</td>
<td>{skill.name}</td>
<td>
<StyledDiv style={{ width: `${skill.level * 10}%`, backgroundColor:`${getColor(skill.level)}` }}></StyledDiv>
<span>{skill.level}</span>
</td>
<td className='media-768'><img src={skill.handsOn ? '/static/images/yes-20px.png' : '/static/images/no-20px.png'}></img></td>
<td className='media-768'><img src={skill.interested ? '/static/images/yes-20px.png' : '/static/images/no-20px.png'}></img></td>
<td className='media-992'>{skill.projects}</td>
</tr>
);
});
};
const skillGroups = Object.keys(skills).map((skillGroup, index) => {
return (
<Fragment key={index}>
<tr>
<th />
<th colSpan={5}>{skillGroup}</th>
</tr>
{<Skill allSkills={skills} skillGroup={skillGroup} />}
</Fragment>
);
});
const Container = (
<div>
<StyledH1>Skills of Sushant Agrawal</StyledH1>
<StyledH4>Contact Sushant for his skills</StyledH4>
<StyledText>{diction.skillset[0]}</StyledText>
<StyledText>{diction.skillset[1]}</StyledText>
<StyledText>{diction.skillset[2]}</StyledText><br></br>
<StyledTable>
<thead>
<tr>
<th>No</th>
<th>Skill name</th>
<th>Skill bar (10 is best)</th>
<th className='media-768'>Hands on</th>
<th className='media-768'>Interested</th>
<th className='media-992'>Experience</th>
</tr>
</thead>
<tbody>{skillGroups}</tbody>
</StyledTable>
</div>
);
return Container;
}
function getColor(value:any) {
const colorScheme:any = {
1: 'grey',
2: 'yellow',
3: 'green',
4: 'blue',
5: 'black',
6: 'magenta',
7: 'cyan',
8: 'red',
9: 'violet',
10: 'red'
}
return(colorScheme[value])
}
const StyledText = styled.div`
margin-bottom:1rem;
font-size: 1.2rem;
margin-left:1rem;
`
const StyledH1 = styled.h1`
font-size: 1.4rem;
margin-left: 1rem;
@media(max-width:992px){
font-size: 1.2rem;
}`
const StyledH4 = styled.h4`
font-size: 1.1rem;
margin-left: 1rem;
@media(max-width:992px){
font-size: 0.8rem;
}`
const StyledTable = styled.table`
thead {
background-color: #dfdfdf;
font-size: 1.1rem;
th {
border: 1px solid #a0a0a0;
}
}
th {
padding-left: 0.5rem;
padding-right: 0.5rem;
border: 1px solid lightgray;
background-color: #f3f3f3;
}
td {
border: 1px solid lightgray;
padding-left: 0.5rem;
padding-right: 0.5rem;
img {
display: block;
margin: auto;
}
span {
vertical-align: middle;
margin-left: 0.1rem;
}
}
font-size: 1.0rem;
border-collapse: collapse;
margin-left:1rem;
.media-768{
@media (max-width:768px){
display:none;
}
}
.media-992{
@media(max-width:992px){
display:none;
}
}
`;
const StyledDiv = styled.div`
display: inline-block;
height: 10px;
border: 2px solid yellow;
vertical-align: middle;
margin-left: 0.3rem;
`;
export default Skillset;
/*
interface skill {
w: string;
b: string;
}
width: ${(props: skill) => props.w + 'px'};
background-color:${(props:skill)=>props.b};
*/
|
capitalch/next
|
adam4/pages/blog.tsx
|
<filename>adam4/pages/blog.tsx<gh_stars>0
import React from 'react'
import Link from 'next/link'
import styled from 'styled-components'
import GlobalStyle from '../handy/globalStyle'
import Layout from '../components/layout'
import Head from '../components/head'
import CodeBlock from '../code-block'
import Comments from '../components/comments'
import axios from 'axios'
// import ReactMarkdown from 'react-markdown/with-html'
import settings from '../settings.json'
function BlogPage({ content, title, pageComments, slug }:any) {
return (
<div>
<GlobalStyle />
<Head title='Blog' />
{/* <Layout>
<StyledLink><Link href='/blogs'><a>Back to blogs</a></Link></StyledLink>
<h3>{title}</h3>
<ReactMarkdown escapeHtml={false} source={content} renderers={{ code: CodeBlock }}>
</ReactMarkdown>
<Comments pageComments={pageComments} slug={slug}></Comments>
</Layout> */}
</div>
);
}
BlogPage.getInitialProps = async ({ res, asPath }:any) => {
try {
const content = res.locals.content
const title = res.locals.title
const slug = asPath.split('/')[2];
const url = `${settings.commentsUrl}/projects`
const params = {
token: settings.token
}
const pageComments = (await axios.get(url, {
params: params
})).data
return {
content
, title
, pageComments
, slug
};
} catch (e:any) {
console.log((e.response && e.response.data.message) || e.message)
}
}
const StyledLink = styled.div`
margin-top:1rem;
`
export default BlogPage
|
capitalch/next
|
adam4/components/header.tsx
|
<gh_stars>0
import React, { useState, useEffect } from 'react'
import Link from 'next/link'
import styled from 'styled-components'
const StyledMenuIcon = styled.div`
div {
width: 35px;
height: 5px;
background-color: #fff;
margin: 6px 0;
}
margin:0.5rem;
margin-left:2rem; // for right alignment after fixed text
cursor:pointer;
@media only screen and (min-width: 993px) {
display:none;
}
`
const StyledMenuItems = styled.ul`
display:flex;
flex-direction:column;
width: 60%;
a {
text-decoration:none;
display:block; // to make whole area clickable
margin-left:1.3rem;
margin-top:0.3rem;
margin-bottom:0.3rem;
font-size:1.3rem;
color:#fff;
}
li {
list-style-type: none;
border: 1px solid white;
border-collapse: collapse;
}
@media only screen and (min-width: 993px) {
flex-direction:row;
align-items:center;
li {
border:0px;
}
}
.active {
color:red;
}
`
const StyledHeader = styled.nav`
grid-area: header;
background-color:black;
display:flex;
justify-content:space-between;
`
const StyledActiveMenuItem = styled.span`
font-weight:700;
font-size:1.3rem;
margin: auto 1rem;
color: #fff;
text-transform:capitalize;
@media only screen and (min-width: 993px) {
display:none;
}
`
const StyledPortfolio = styled.span`
font-size:1rem;
font-weight:bold;
color:#fff;
margin-left: auto;
margin-top:auto;
margin-bottom:auto;
margin-right:0.5rem;
`
function MenuIcon({ show, setShow, portfolio, setPortfolio }:any): any {
return <StyledMenuIcon onClick={() => { setShow(!show); setPortfolio(!portfolio) }}>
<div></div>
<div></div>
<div></div>
</StyledMenuIcon>
}
function Header({ currentPage }:any) {
const [show, setShow] = useState(false)
const [portfolio, setPortfolio] = useState(true)
function screenTest(e:any) {
e.matches ? setShow(true) : setShow(false)
}
useEffect(() => {
const width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
if (width >= 993) { (setShow(true)); setPortfolio(true) }
const mql = window.matchMedia('(min-width: 992px)')
mql.addListener(screenTest)
return () => mql.removeListener(screenTest)
})
return <StyledHeader>
{show && <MenuItems></MenuItems>}
{(!show) && <StyledActiveMenuItem>{currentPage}</StyledActiveMenuItem>}
{(portfolio) && <StyledPortfolio>Portfolio of Sushant</StyledPortfolio>}
{<MenuIcon show={show} setShow={setShow} portfolio={portfolio} setPortfolio={setPortfolio}></MenuIcon>}
</StyledHeader>
function MenuItems() {
return <StyledMenuItems>
<li><Link href='/'>{XAnchor('Home')}</Link></li>
<li><Link href='/' as='/about'>{XAnchor('About')}</Link></li>
<li><Link href='/' as='/contact'>{XAnchor('Contact')}</Link></li>
<li><Link href='/' as='/resume'>{XAnchor('Resume')}</Link></li>
<li><Link href='/' as='/skillset'>{XAnchor('Skillset')}</Link></li>
<li><Link href='/' as='/academics'>{XAnchor('Academics')}</Link></li>
<li><Link href='/' as='/projects'>{XAnchor('Projects')}</Link></li>
<li><Link href='/' as='/qa'>{XAnchor('QA')}</Link></li>
<li><Link href='/blogs' as='/blogs'>{XAnchor('Blogs')}</Link></li>
{/* <li><Link href='/blogs' as='/blogs'><a onClick={() => { setShow(false); setPortfolio(true) }}>Blogs</a></Link></li> */}
{/* <li><button style={{ marginLeft: '1rem' }} onClick={() => { newComment() }}>New comment</button></li>
<li><button style={{ marginLeft: '1rem' }} onClick={() => { deleteComment() }}>Delete comment</button></li>
<li><button style={{ marginLeft: '1rem' }} onClick={() => { getComments() }}>Get comments</button></li> */}
{/* <li><button style={{ marginLeft: '1rem' }} onClick={() => { makeTree() }}>Tree</button></li> */}
</StyledMenuItems>
function XAnchor(x:any) {
return <a style={{ color: `${getColor(x)}` }} onClick={() => {
setShow(false);
setPortfolio(true);
}}>{x}</a>
}
function getColor(x: string) {
if (x.toLowerCase() === currentPage.toLowerCase()) {
return 'aquamarine'
} else {
return 'white'
}
}
}
}
export default Header
/*
*/
|
amrtaher1234/Crypto-notifier-nest
|
src/user/user.controller.ts
|
import { Body, Controller, Get, Param, Post } from '@nestjs/common';
import { FinanceService } from 'src/shared/finance/finance.service';
import { SubscribeUserDto } from './dtos/user.dto';
import { UserService } from './user.service';
@Controller('users')
export class UserController {
constructor(
private readonly userService: UserService,
private readonly financeService: FinanceService,
) {}
@Get()
async getAllUsers() {
return await this.userService.getAllUsers();
}
@Get('/symbol/:symb')
async getSymbol(@Param() params) {
return await this.financeService.getSymbolQuote(params.symb);
}
@Post('/subscribe')
async subscribeUser(@Body() subscribeUserDto: SubscribeUserDto) {
await this.userService.subscribeUser(
subscribeUserDto.id,
subscribeUserDto.resourceData,
);
return {
message: 'successfuflly subscribed',
};
}
}
|
amrtaher1234/Crypto-notifier-nest
|
src/user/dtos/user.dto.ts
|
<reponame>amrtaher1234/Crypto-notifier-nest<gh_stars>0
export class CreateUserDto {
name: string;
email: string;
resource?: CreateResourceDto;
}
export class CreateResourceDto {
min: number;
max: number;
resource: string;
}
export class SubscribeUserDto {
id: string;
resourceData: CreateResourceDto;
}
|
amrtaher1234/Crypto-notifier-nest
|
src/schemas/user.schema.ts
|
<reponame>amrtaher1234/Crypto-notifier-nest
import { Prop, Schema, SchemaFactory, raw } from '@nestjs/mongoose';
import { Document, Schema as MongooseSchema } from 'mongoose';
import { Resource } from './resource.schema';
export type UserDocument = User & Document;
@Schema()
export class User {
@Prop()
name: string;
@Prop()
email: string;
@Prop({
type: [
{
min: { type: Number },
max: { type: Number },
resource: { type: MongooseSchema.Types.ObjectId, ref: 'Resource' },
},
],
})
resources: { min: number; max: number; resource: Resource }[];
}
export const UserSchema = SchemaFactory.createForClass(User);
|
amrtaher1234/Crypto-notifier-nest
|
src/user/user.module.ts
|
<reponame>amrtaher1234/Crypto-notifier-nest
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { MailModule } from 'src/mail/mail.module';
import { Resource, ResourceSchema } from 'src/schemas/resource.schema';
import { User, UserSchema } from 'src/schemas/user.schema';
import { SharedModule } from 'src/shared/shared.module';
import { UserController } from './user.controller';
import { UserService } from './user.service';
@Module({
imports: [
MailModule,
SharedModule,
MongooseModule.forFeature([
{
name: User.name,
schema: UserSchema,
collection: 'users',
},
{
name: Resource.name,
schema: ResourceSchema,
collection: 'resources',
},
]),
],
providers: [UserService],
controllers: [UserController],
exports: [UserService],
})
export class UserModule {}
|
amrtaher1234/Crypto-notifier-nest
|
src/mail/mail.service.ts
|
import { MailerService } from '@nestjs-modules/mailer';
import { Injectable } from '@nestjs/common';
import { SendResourceMailDto } from './mail.dto';
@Injectable()
export class MailService {
constructor(private mailerService: MailerService) {}
async sendMailForResouce(sendResourceMail: SendResourceMailDto) {
const { quotes, userEmail } = sendResourceMail;
await this.mailerService.sendMail({
to: userEmail,
subject: `Your subscribed resources (${quotes
.map((quote) => quote.shortName)
.join(', ')}) has been changed!`,
template: './resource',
context: {
...sendResourceMail,
},
});
}
async sendMail() {
await this.mailerService.sendMail({
to: '<EMAIL>',
subject: 'Welcome to Nice App! Confirm your Email',
template: './test',
context: {
name: 'Ahmed',
},
});
}
}
|
amrtaher1234/Crypto-notifier-nest
|
src/mail/mail.dto.ts
|
import { Quote } from 'yahoo-finance2/dist/esm/src/modules/quote';
export class SendResourceMailDto {
userName: string;
userEmail: string;
quotes: Quote[];
}
|
amrtaher1234/Crypto-notifier-nest
|
src/schemas/resource.schema.ts
|
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
export type ResourceDocument = Resource & Document;
@Schema()
export class Resource {
@Prop()
name: string;
@Prop()
symbol: string;
}
export const ResourceSchema = SchemaFactory.createForClass(Resource);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.