Skip to content

Commit

Permalink
add more endpoints to sample service
Browse files Browse the repository at this point in the history
  • Loading branch information
akshay288 committed Mar 13, 2023
1 parent 073c43d commit cd76240
Show file tree
Hide file tree
Showing 9 changed files with 253 additions and 0 deletions.
6 changes: 6 additions & 0 deletions ingestors/test_data/producers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
from producers.ecommerce.new_cart import EcommerceMakeCartProducer
from producers.ecommerce.add_product_to_cart import EcommerceAddProductToCartProducer
from producers.ecommerce.edit_product import EcommerceEditProductProducer
from producers.ecommerce.edit_product_price import EcommerceEditProductPriceProducer
from producers.ecommerce.register import EcommerceRegisterProducer
from producers.ecommerce.edit_admin_config import EcommerceEditAdminConfigProducer
from producers.ecommerce.get_admin_config import EcommerceGetAdminConfigProducer
from producers.paymentprocessor.add_billing import PaymentProcessorAddBillingProducer
from producers.paymentprocessor.get_billing import PaymentProcessorGetBillingProducer
from producers.paymentprocessor.add_charge import PaymentProcessorAddChargeProducer
Expand All @@ -21,11 +24,14 @@
"ecommerce_make_cart": EcommerceMakeCartProducer,
"ecommerce_make_product": EcommerceMakeProductProducer,
"ecommerce_edit_product": EcommerceEditProductProducer,
"ecommerce_edit_product_price": EcommerceEditProductPriceProducer,
"ecommerce_make_purchase": EcommerceMakePurchaseProducer,
"ecommerce_login": EcommerceLoginProducer,
"ecommerce_register": EcommerceRegisterProducer,
"ecommerce_get_product": EcommerceGetProductProducer,
"ecommerce_get_cart": EcommerceGetCartProducer,
"ecommerce_edit_admin_config": EcommerceEditAdminConfigProducer,
"ecommerce_get_admin_config": EcommerceGetAdminConfigProducer,
"payment_processor_user": PaymentProcessorUserProducer,
"payment_processor_user_verify": PaymentProcessorUserVerifyProducer,
"payment_processor_get_user": PaymentProcessorGetUserProducer,
Expand Down
44 changes: 44 additions & 0 deletions ingestors/test_data/producers/ecommerce/edit_admin_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from datetime import datetime, timedelta
from typing import List
import json
from random import randint

from producers.ecommerce.utils import sources, destinations
from producers.utils import get_auth_header, get_meta, JSON_HEADER
from producers.base import BaseProducer


class EcommerceEditAdminConfigProducer(BaseProducer):

avg_emit_delta = timedelta(seconds=60)

def get_data_points_helper(self) -> dict:
resp = {
"status": 200,
"headers": [JSON_HEADER],
"body": json.dumps({
"ok": True,
}),
}
req_body = {
"max_products": randint(100, 1000),
"max_carts": randint(10000, 100000),
"foo": "bar",
}
return {
"request": {
"url": {
"host": "test-ecommerce.metlo.com",
"path": "/admin/config",
"parameters": []
},
"headers": [get_auth_header()],
"method": "POST",
"body": json.dumps(req_body),
},
"response": resp,
"meta": get_meta(sources, destinations),
}

def get_data_points(self, time: datetime) -> List[dict]:
return [self.get_data_points_helper()]
44 changes: 44 additions & 0 deletions ingestors/test_data/producers/ecommerce/edit_product_price.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from datetime import datetime, timedelta
from typing import List
from uuid import uuid4
import json
from random import randint

from producers.ecommerce.utils import sources, destinations
from producers.utils import get_auth_header, get_meta, JSON_HEADER
from producers.base import BaseProducer


class EcommerceEditProductPriceProducer(BaseProducer):

avg_emit_delta = timedelta(seconds=30)

def get_data_points_helper(self) -> dict:
product_uuid = str(uuid4())
resp = {
"status": 200,
"headers": [JSON_HEADER],
"body": json.dumps({
"ok": True,
}),
}
req_body = {
"price": randint(100, 1000),
}
return {
"request": {
"url": {
"host": "test-ecommerce.metlo.com",
"path": f"/product/{product_uuid}/price",
"parameters": []
},
"headers": [get_auth_header()],
"method": "POST",
"body": json.dumps(req_body),
},
"response": resp,
"meta": get_meta(sources, destinations),
}

def get_data_points(self, time: datetime) -> List[dict]:
return [self.get_data_points_helper()]
40 changes: 40 additions & 0 deletions ingestors/test_data/producers/ecommerce/get_admin_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from datetime import datetime, timedelta
from typing import List
import json
from random import randint

from producers.ecommerce.utils import sources, destinations
from producers.utils import get_auth_header, get_meta, JSON_HEADER
from producers.base import BaseProducer


class EcommerceGetAdminConfigProducer(BaseProducer):

avg_emit_delta = timedelta(seconds=60)

def get_data_points_helper(self) -> dict:
resp = {
"status": 200,
"headers": [JSON_HEADER],
"body": json.dumps({
"max_products": randint(100, 1000),
"max_carts": randint(10000, 100000),
"foo": "bar",
}),
}
return {
"request": {
"url": {
"host": "test-ecommerce.metlo.com",
"path": f"/admin/config",
"parameters": []
},
"headers": [get_auth_header()],
"method": "GET",
},
"response": resp,
"meta": get_meta(sources, destinations),
}

def get_data_points(self, time: datetime) -> List[dict]:
return [self.get_data_points_helper()]
46 changes: 46 additions & 0 deletions sample-service/sample-client/init_testing_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,28 @@ def main(backend, api_key):
print(r.text)
return

r = requests.post(
f"{backend}/register",
json={
"firstName": "Test 1",
"lastName": "Admin User 1",
"email": "[email protected]",
"role": "admin",
"address": fake.address(),
"phoneNumber": fake.phone_number(),
"dob": fake.date_of_birth().isoformat(),
"password": fake.sentence(nb_words=5),
},
headers=headers
)
if r.status_code > 300:
print("Register Admin User 1")
print(r.status_code)
print(r.text)
return
admin_user_1 = r.json()['user']
admin_user_1_api_key = admin_user_1['apiKey']

r = requests.post(
f"{backend}/register",
json={
Expand Down Expand Up @@ -105,12 +127,19 @@ def main(backend, api_key):
actor User {{
items = [
{{
"uuid": "{admin_user_1['uuid']}",
"role": "admin",
"auth": "{admin_user_1['apiKey']}"
}},
{{
"uuid": "{user_1['uuid']}",
"role": "regular",
"auth": "{user_1['apiKey']}"
}},
{{
"uuid": "{user_2['uuid']}",
"role": "regular",
"auth": "{user_2['apiKey']}"
}}
]
Expand Down Expand Up @@ -142,6 +171,23 @@ def main(backend, api_key):
]
}}
resource AdminAccess {{
permissions = ["read", "write"],
endpoints = [
{{
"method": "GET",
"path": "/admin/.*",
"permissions": ["read"]
}},
{{
"method": "POST",
"path": "/admin/.*",
"permissions": ["write"]
}}
]
}}
has_permission(User(role="admin"), [ "read", "write" ], AdminAccess)
has_permission(User, [ "read" ], Product)
has_permission(User(role="admin"), [ "write" ], Product)
has_permission(User(uuid="{user_1['uuid']}"), [ "write" ], Product(uuid="{user_1_product}"))
Expand Down
34 changes: 34 additions & 0 deletions sample-service/sample-ecommerce/src/api/admin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { FastifyReply, FastifyRequest } from "fastify"
import ApiResponseHandler from "api-response-handler"
import { Error401UnauthorizedRequest } from "errors"

export const getAdminConfig = async (
req: FastifyRequest,
res: FastifyReply,
): Promise<void> => {
try {
await ApiResponseHandler.success(res, {
max_products: 200,
max_carts: 15000,
foo: "bar",
})
} catch (err) {
await ApiResponseHandler.error(res, err)
}
}

export const editAdminConfig = async (
req: FastifyRequest,
res: FastifyReply,
): Promise<void> => {
try {
if (req.user.role != "admin") {
throw new Error401UnauthorizedRequest("No access")
}
await ApiResponseHandler.success(res, {
ok: true,
})
} catch (err) {
await ApiResponseHandler.error(res, err)
}
}
19 changes: 19 additions & 0 deletions sample-service/sample-ecommerce/src/api/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,25 @@ export const editProductHandler = async (
}
}

export const editProductPriceHandler = async (
req: FastifyRequest,
res: FastifyReply,
): Promise<void> => {
try {
const { productUuid } = req.params as { productUuid: string }
const editNewProductParams: AddNewProductParams =
req.body as AddNewProductParams
await ProductService.editProductPrice(
productUuid,
editNewProductParams,
req.user,
)
await ApiResponseHandler.success(res, "OK")
} catch (err) {
await ApiResponseHandler.error(res, err)
}
}

export const getProductsHandler = async (
req: FastifyRequest,
res: FastifyReply,
Expand Down
6 changes: 6 additions & 0 deletions sample-service/sample-ecommerce/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ import {
import {
createNewProductHandler,
editProductHandler,
editProductPriceHandler,
getProductHandler,
getProductsHandler,
} from "api/product"
import { UserService } from "services/user"
import { Error401UnauthorizedRequest } from "errors"
import ApiResponseHandler from "api-response-handler"
import { editAdminConfig, getAdminConfig } from "api/admin"

dotenv.config()

Expand Down Expand Up @@ -96,8 +98,12 @@ app.register((fastify, options, next) => {
fastify.get("/product", getProductsHandler)
fastify.get("/product/:productUuid", getProductHandler)
fastify.post("/product/:productUuid", editProductHandler)
fastify.post("/product/:productUuid/price", editProductPriceHandler)
fastify.post("/product/new", createNewProductHandler)

fastify.get("/admin/config", getAdminConfig)
fastify.post("/admin/config", editAdminConfig)

fastify.post("/product/new/form", async function (req, res) {
try {
const data = await req.body
Expand Down
14 changes: 14 additions & 0 deletions sample-service/sample-ecommerce/src/services/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,20 @@ import { AddNewProductParams } from "types"
import { NEW_VAL_LIMIT } from "utils"

export class ProductService {
static async editProductPrice(
uuid: string,
params: AddNewProductParams,
user: User,
) {
const { price } = params
if (!price) {
throw new Error400BadRequest("Please provide product price.")
}
let product = await ProductService.getProduct(uuid, user)
product.price = price
product.save()
}

static async editProduct(
uuid: string,
params: AddNewProductParams,
Expand Down

0 comments on commit cd76240

Please sign in to comment.