JavaScript · API · Средний
Заказы
Оформляйте заказы из корзины и просматривайте историю заказов.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
Оформление и получение заказов
#Справочник эндпоинтов заказов
#Упражнения:
Оформить заказ
#Добавьте хотя бы один товар в корзину, затем отправьте POST к `/api/orders/` с номером телефона. Выведите `id` и `status` заказа.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. авторизоваться
// 2. добавить товар в корзину
// 3. POST /api/orders/ и вывести id + status
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const slug = await fetch(`${BASE_URL}/api/products/`).then(r => r.json())
.then(d => d.results[0].slug);
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: slug, quantity: 1 }),
});
const order = await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
}).then(r => r.json());
console.log(order.id);
console.log(order.status);
}
main();
Список заказов
#Получите историю заказов через GET `/api/orders/`. Выведите общее количество и `id` и `status` каждого заказа.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// GET /api/orders/ и вывести количество + id и status каждого заказа
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = { 'Authorization': `Token ${token}` };
const data = await fetch(`${BASE_URL}/api/orders/`, { headers }).then(r => r.json());
console.log(`${data.count} orders`);
for (const order of data.results) {
console.log(`#${order.id} — ${order.status}`);
}
}
main();
Детали заказа
#Оформите заказ, затем получите его детали через GET `/api/orders/{id}/`. Выведите `name`, `quantity` и `price` для каждой позиции.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// оформить заказ затем получить его детали
// вывести name, quantity, price каждой позиции
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const products = await fetch(`${BASE_URL}/api/products/`).then(r => r.json());
for (const p of products.results.slice(0, 2)) {
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: p.slug, quantity: 1 }),
});
}
const order = await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
}).then(r => r.json());
const detail = await fetch(`${BASE_URL}/api/orders/${order.id}/`, { headers }).then(r => r.json());
for (const item of detail.items) {
console.log(item.name, item.quantity, item.price);
}
}
main();
Полный поток заказа
#В одном скрипте: авторизуйтесь, добавьте 3 товара в корзину, оформите заказ, убедитесь что он есть в списке заказов. Выведите id заказа и количество позиций.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// полный поток: авторизация → 3 товара → заказ → подтвердить в списке
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const products = await fetch(`${BASE_URL}/api/products/`).then(r => r.json());
for (const p of products.results.slice(0, 3)) {
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: p.slug, quantity: 1 }),
});
}
const order = await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
}).then(r => r.json());
const history = await fetch(`${BASE_URL}/api/orders/`, { headers }).then(r => r.json());
const ids = history.results.map(o => o.id);
console.log(`Order ${order.id} in list: ${ids.includes(order.id)}`);
console.log(`Items: ${order.items.length}`);
}
main();
Подсчитать общие расходы
#Оформите два отдельных заказа (добавьте товары → заказ → ещё товары → заказ). Затем получите все заказы и подсчитайте общие расходы по всем позициям. Выведите сумму.
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// оформить 2 заказа, затем просуммировать цены всех позиций
}
main();
Решение
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const { token } = await fetch(`${BASE_URL}/api/auth/token/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }),
}).then(r => r.json());
const headers = {
'Authorization': `Token ${token}`,
'Content-Type': 'application/json',
};
const products = await fetch(`${BASE_URL}/api/products/`).then(r => r.json());
// First order
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: products.results[0].slug, quantity: 1 }),
});
await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
});
// Second order
await fetch(`${BASE_URL}/api/cart/items/`, {
method: 'POST', headers,
body: JSON.stringify({ product_slug: products.results[1].slug, quantity: 2 }),
});
await fetch(`${BASE_URL}/api/orders/`, {
method: 'POST', headers,
body: JSON.stringify({ phone_number: '+1234567890' }),
});
const allOrders = await fetch(`${BASE_URL}/api/orders/`, { headers }).then(r => r.json());
const totalSpend = allOrders.results.reduce((sum, order) =>
sum + order.items.reduce((s, item) =>
s + parseFloat(item.price) * item.quantity, 0
), 0
);
console.log(`Total spend: ${totalSpend.toFixed(2)}`);
}
main();