Skip to content

Commit

Permalink
working _id queries and save() re: stargate/data-api#1359
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Aug 27, 2024
1 parent 321dfbf commit 189cde8
Show file tree
Hide file tree
Showing 26 changed files with 101 additions and 128 deletions.
4 changes: 2 additions & 2 deletions discord-bot/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ Create table:

```
CREATE TABLE bots (
id text,
"_id" text,
name text,
PRIMARY KEY (id));
PRIMARY KEY ("_id"));
```
2 changes: 1 addition & 1 deletion discord-bot/commands/createdocument.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module.exports = {
data: new SlashCommandBuilder().setName('createdocument').setDescription('creates a document'),
async execute(interaction) {
console.log(new Date(), 'createdocument');
await Bot.insertMany([{ name: 'I am a document' }]);
await Bot.create({ name: 'I am a document' });
await interaction.reply('done!');
}
};
7 changes: 1 addition & 6 deletions discord-bot/models/bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,8 @@
const mongoose = require('../mongoose');

const botSchema = new mongoose.Schema({
id: {
type: mongoose.Types.ObjectId,
required: true,
default: () => new mongoose.Types.ObjectId()
},
name: String
}, { _id: false, versionKey: false });
}, { versionKey: false });

const Bot = mongoose.model('Bot', botSchema);

Expand Down
2 changes: 1 addition & 1 deletion discord-bot/test/countdocuments.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe('countdocuments', function() {
it('returns the number of bot documents', async function() {
const docs = await Bot.find({});
for (const doc of docs) {
await Bot.deleteOne({ id: doc.id });
await Bot.deleteOne({ _id: doc._id });
}
await Bot.insertMany({ name: 'test' });

Expand Down
2 changes: 1 addition & 1 deletion discord-bot/test/createdocument.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ describe('createdocument', function() {
it('inserts a new document', async function() {
let docs = await Bot.find({});
for (const doc of docs) {
await Bot.deleteOne({ id: doc.id });
await Bot.deleteOne({ _id: doc._id });
}

const interaction = {
Expand Down
2 changes: 1 addition & 1 deletion discord-bot/test/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ before(async function() {

const docs = await Bot.find({});
for (const doc of docs) {
await Bot.deleteOne({ id: doc.id });
await Bot.deleteOne({ _id: doc._id });
}
});

Expand Down
28 changes: 14 additions & 14 deletions netlify-functions-ecommerce/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,26 +77,26 @@ Using test

```
CREATE TABLE products (
id text,
"_id" text,
name text,
price decimal,
image text,
description text,
PRIMARY KEY (id));
PRIMARY KEY ("_id"));
CREATE TABLE orders (
id text,
total decimal,
name text,
paymentMethod text,
items text,
PRIMARY KEY (id));
"_id" text,
total decimal,
name text,
"paymentMethod" text,
items text,
PRIMARY KEY ("_id"));
CREATE TABLE carts (
id text,
items text,
orderId text,
total decimal,
stripeSessionId text,
PRIMARY KEY (id));
"_id" text,
items text,
"orderId" text,
total decimal,
"stripeSessionId" text,
PRIMARY KEY ("_id"));
```
49 changes: 24 additions & 25 deletions netlify-functions-ecommerce/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,29 @@
const mongoose = require('./mongoose');

const productSchema = new mongoose.Schema({
id: {
type: mongoose.Types.ObjectId,
required: true,
default: () => new mongoose.Types.ObjectId()
},
name: String,
price: Number,
image: String,
description: String
}, { _id: false, versionKey: false });
}, { versionKey: false });

const Product = mongoose.model('Product', productSchema);

module.exports.Product = Product;

const orderSchema = new mongoose.Schema({
id: {
type: mongoose.Types.ObjectId,
required: true,
default: () => new mongoose.Types.ObjectId()
items: {
type: String,
get(v) {
return v == null ? v : JSON.parse(v);
},
set(v) {
if (v == null) {
return v;
}
return typeof v === 'string' ? v : JSON.stringify(v);
},

Check warning on line 27 in netlify-functions-ecommerce/models.js

View workflow job for this annotation

GitHub Actions / Ecommerce Sample App (16, ubuntu-20.04)

Unexpected trailing comma

Check warning on line 27 in netlify-functions-ecommerce/models.js

View workflow job for this annotation

GitHub Actions / Ecommerce Sample App (16, ubuntu-20.04)

Unexpected trailing comma
},
items: [{
_id: false,
productId: { type: mongoose.ObjectId, required: true, ref: 'Product' },
quantity: { type: Number, required: true, validate: v => v > 0 }
}],
total: {
type: Number,
default: 0
Expand All @@ -37,22 +34,24 @@ const orderSchema = new mongoose.Schema({
type: String
},
paymentMethod: {
id: String,
brand: String,
last4: String
type: String,
get(v) {
return v == null ? v : JSON.parse(v);
},
set(v) {
if (v == null) {
return v;
}
return typeof v === 'string' ? v : JSON.stringify(v);
},

Check warning on line 46 in netlify-functions-ecommerce/models.js

View workflow job for this annotation

GitHub Actions / Ecommerce Sample App (16, ubuntu-20.04)

Unexpected trailing comma

Check warning on line 46 in netlify-functions-ecommerce/models.js

View workflow job for this annotation

GitHub Actions / Ecommerce Sample App (16, ubuntu-20.04)

Unexpected trailing comma
}
}, { _id: false, versionKey: false });
}, { versionKey: false });

const Order = mongoose.model('Order', orderSchema);

module.exports.Order = Order;

const cartSchema = new mongoose.Schema({
id: {
type: mongoose.Types.ObjectId,
required: true,
default: () => new mongoose.Types.ObjectId()
},
items: {
type: String,
get(v) {
Expand All @@ -68,7 +67,7 @@ const cartSchema = new mongoose.Schema({
orderId: { type: mongoose.ObjectId, ref: 'Order' },
total: Number,
stripeSessionId: { type: String }
}, { _id: false, versionKey: false, timestamps: false, toObject: { getters: true }, toJSON: { getters: true } });
}, { versionKey: false, timestamps: false, toObject: { getters: true }, toJSON: { getters: true } });

cartSchema.virtual('numItems').get(function numItems() {
if (this.items == null) {
Expand Down
6 changes: 3 additions & 3 deletions netlify-functions-ecommerce/netlify/functions/addToCart.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const handler = async(event) => {
if (event.body.cartId) {
// get the document containing the specified cartId
const cart = await Cart.
findOne({ id: event.body.cartId }).
findOne({ _id: event.body.cartId }).
setOptions({ sanitizeFilter: true });

if (cart == null) {
Expand All @@ -31,7 +31,7 @@ const handler = async(event) => {
for (const product of event.body.items) {
const exists = cart.items?.find(item => item?.productId?.toString() === product?.productId?.toString());
if (!exists) {
if (products.find(p => product?.productId?.toString() === p?.id?.toString())) {
if (products.find(p => product?.productId?.toString() === p?._id?.toString())) {
cart.items = [...(cart.items || []), product];
}
} else {
Expand All @@ -46,7 +46,7 @@ const handler = async(event) => {
return { statusCode: 200, body: JSON.stringify({ cart: null }) };
}

await Cart.updateOne({ id: cart.id }, cart.getChanges());
await cart.save();
return { statusCode: 200, body: JSON.stringify(cart) };
} else {
// If no cartId, create a new cart
Expand Down
8 changes: 4 additions & 4 deletions netlify-functions-ecommerce/netlify/functions/checkout.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@ const handler = async(event) => {
event.body = JSON.parse(event.body || {});
await connect();
const cart = await Cart.
findOne({ id: event.body.cartId }).
findOne({ _id: event.body.cartId }).
setOptions({ sanitizeFilter: true }).
orFail();

const stripeProducts = { line_items: [] };
let total = 0;
for (let i = 0; i < cart.items.length; i++) {
const product = await Product.findOne({ id: cart.items[i].productId });
const product = await Product.findOne({ _id: cart.items[i].productId });
stripeProducts.line_items.push({
price_data: {
currency: 'usd',
Expand All @@ -35,7 +35,7 @@ const handler = async(event) => {
cart.total = total;

if (process.env.STRIPE_SECRET_KEY === 'test') {
await Cart.updateOne({ id: cart.id }, cart.getChanges());
await cart.save();
return {
statusCode: 200,
body: JSON.stringify({ cart: cart, url: '/order-confirmation' })
Expand All @@ -50,7 +50,7 @@ const handler = async(event) => {
});

cart.stripeSessionId = session.id;
await Cart.updateOne({ id: cart.id }, cart.getChanges());
await cart.save();

return {
statusCode: 200,
Expand Down
14 changes: 7 additions & 7 deletions netlify-functions-ecommerce/netlify/functions/confirmOrder.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ const handler = async(event) => {
event.body = JSON.parse(event.body || {});
await connect();
const cart = await Cart.
findOne({ id: event.body.cartId }).
findOne({ _id: event.body.cartId }).
setOptions({ sanitizeFilter: true }).
orFail();

if (cart.orderId) {
const order = await Order.findOne({ id: cart.orderId }).orFail();
const order = await Order.findOne({ _id: cart.orderId }).orFail();

return {
statusCode: 200,
Expand All @@ -35,8 +35,8 @@ const handler = async(event) => {
}
});

cart.orderId = order.id;
await Cart.updateOne({ id: cart.id }, cart.getChanges());
cart.orderId = order._id;
await cart.save();

return {
statusCode: 200,
Expand All @@ -55,7 +55,7 @@ const handler = async(event) => {
const intent = await stripe.paymentIntents.retrieve(session.payment_intent);
const paymentMethod = await stripe.paymentMethods.retrieve(intent['payment_method']);

const [order] = await Order.insertMany({
const order = await Order.create({
items: cart.items,
name: session['customer_details'].name,
total: +(session['amount_total'] / 100).toFixed(2),
Expand All @@ -64,8 +64,8 @@ const handler = async(event) => {
null
});

cart.orderId = order.id;
await Cart.updateOne({ id: cart.id }, cart.getChanges());
cart.orderId = order._id;
await cart.save();

return {
statusCode: 200,
Expand Down
2 changes: 1 addition & 1 deletion netlify-functions-ecommerce/netlify/functions/getCart.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const handler = async(event) => {
await connect();
// get the document containing the specified cartId
const cart = await Cart.
findOne({ id: event.queryStringParameters.cartId }).
findOne({ _id: event.queryStringParameters.cartId }).
setOptions({ sanitizeFilter: true });
return { statusCode: 200, body: JSON.stringify({ cart }) };
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const handler = async(event) => {
try {
event.body = JSON.parse(event.body || {});
await connect();
const cart = await Cart.findOne({ id: event.body.cartId });
const cart = await Cart.findOne({ _id: event.body.cartId });
const index = cart.items.findIndex((item) =>
item.productId.toString() == event.body.item.productId.toString()
);
Expand All @@ -32,7 +32,7 @@ const handler = async(event) => {
...cart.items.slice(index + 1)
];
}
await Cart.updateOne({ id: cart.id }, cart.getChanges());
await cart.save();
return { statusCode: 200, body: JSON.stringify(cart) };
} catch (error) {
console.log(error);
Expand Down
10 changes: 5 additions & 5 deletions netlify-functions-ecommerce/test/addToCart.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ describe('Add to Cart', function() {
body: {
cartId: cart.id,
items: [
{ productId: products[0].id, quantity: 2 },
{ productId: products[1].id, quantity: 1 }
{ productId: products[0]._id, quantity: 2 },
{ productId: products[1]._id, quantity: 1 }
]
}
};
Expand All @@ -58,10 +58,10 @@ describe('Add to Cart', function() {
const { cart } = await fixtures.createCart({ products: [] });
const params = {
body: {
cartId: cart.id,
cartId: cart._id,
items: [
{ productId: products[0].id, quantity: 2 },
{ productId: products[1].id, quantity: 1 }
{ productId: products[0]._id, quantity: 2 },
{ productId: products[1]._id, quantity: 1 }
]
}
};
Expand Down
6 changes: 3 additions & 3 deletions netlify-functions-ecommerce/test/checkout.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ describe('Checkout', function() {
body: {
cartId: null,
items: [
{ productId: products[0].id, quantity: 2 },
{ productId: products[1].id, quantity: 1 }
{ productId: products[0]._id, quantity: 2 },
{ productId: products[1]._id, quantity: 1 }
]
}
};
Expand All @@ -33,7 +33,7 @@ describe('Checkout', function() {
assert(result.body);
assert(result.body.items.length);

params.body.cartId = result.body.id;
params.body.cartId = result.body._id;
sinon.stub(stripe.paymentIntents, 'retrieve').returns({ status: 'succeeded', id: '123', brand: 'visa', last4: '1234' });
sinon.stub(stripe.paymentMethods, 'retrieve').returns({ status: 'succeeded', id: '123', brand: 'visa', last4: '1234' });
sinon.stub(stripe.checkout.sessions, 'create').returns({
Expand Down
2 changes: 1 addition & 1 deletion netlify-functions-ecommerce/test/fixtures/createCart.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
const { Cart } = require('../../models');

module.exports = async function createCart(params) {
const [cart] = await Cart.insertMany({ items: params.items });
const cart = await Cart.create({ items: params.items });
return { cart };
};
3 changes: 1 addition & 2 deletions netlify-functions-ecommerce/test/fixtures/createOrder.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const { Order } = require('../../models');

module.exports = async function createOrder(params) {

const [order] = await Order.insertMany(params.order);
const [order] = await Order.create(params.order);
return { order };
};
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const { Product } = require('../../models');

module.exports = async function createProducts(params) {
const products = await Product.insertMany(params.product);
const products = await Product.create(params.product);

return { products };
};
Loading

0 comments on commit 189cde8

Please sign in to comment.