IT |
気になる、記になる… |
「iPhone 13 Pro」のアルパイングリーンモデルの実機写真 |
https://taisy0.com/2022/03/09/154401.html
|
apple |
2022-03-09 12:55:56 |
IT |
気になる、記になる… |
ワイモバイル、「iPhone SE (第3世代)」の機種代金を発表 |
https://taisy0.com/2022/03/09/154399.html
|
iphone |
2022-03-09 12:48:22 |
IT |
気になる、記になる… |
Microsoft、「Surface Pro 7+」「Surface Laptop Studio」「Surface Laptop Go」向けに2022年3月のファームウェアアップデートをリリース |
https://taisy0.com/2022/03/09/154397.html
|
microsoft |
2022-03-09 12:17:12 |
IT |
気になる、記になる… |
「クロノ・トリガー」のSTEAM/スマホ版が最大21:9までの全画面表示に対応へ − 操作性向上なども |
https://taisy0.com/2022/03/09/154393.html
|
steam |
2022-03-09 12:09:20 |
AWS |
AWS Database Blog |
Hidden dangers of duplicate key violations in PostgreSQL and how to avoid them |
https://aws.amazon.com/blogs/database/hidden-dangers-of-duplicate-key-violations-in-postgresql-and-how-to-avoid-them/
|
Hidden dangers of duplicate key violations in PostgreSQL and how to avoid themA common coding strategy is to have multiple application servers attempt to insert the same data into the same table at the same time and rely on the database unique constraint to prevent duplication The “duplicate key violates unique constraint error notifies the caller that a retry is needed This seems like an intuitive approach … |
2022-03-09 12:38:45 |
Linux |
Ubuntuタグが付けられた新着投稿 - Qiita |
ubuntuでboot usb 作成 |
https://qiita.com/hoshianaaa/items/54804cc31fa821a7247c
|
bootusb |
2022-03-09 21:07:00 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
【Github】ローカルリポジトリからリモートリポジトリへ初回コミット&プッシュ |
https://qiita.com/kurosuke1117/items/5b5d94c66ac80922e06a
|
urlgitpushuoriginmain |
2022-03-09 21:37:41 |
Git |
Gitタグが付けられた新着投稿 - Qiita |
gitの初期化コマンド(初学者) |
https://qiita.com/ume-bar/items/307bc04273fb6cfd1a7c
|
gitの初期化コマンド初学者まずは、GitHubに登録してアカウントを取得します。 |
2022-03-09 21:23:45 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
Heroku × Rails × MySQL でアプリケーションをデプロイする際のトラブルシューティング集 |
https://qiita.com/noraworld/items/09dac6e4340b85e35be4
|
含まれている環境変数使用されているDBJAWSDBURLJawsDBCLEARDBDATABASEURLClearDB補足読み飛ばし可環境変数JAWSDBURLまたはCLEARDBDATABASEURLの先頭がmysqlとなっているが、urlに指定する際はmysqlに変更するのがポイント。 |
2022-03-09 21:30:14 |
技術ブログ |
Developers.IO |
내부 ALB(Application Load Balancer) 구성해 보기 |
https://dev.classmethod.jp/articles/try-to-configure-the-internal-application-load-balancer/
|
내부ALB Application Load Balancer 구성해보기안녕하세요클래스메소드김재욱 Kim Jaewook 입니다 이번에는내부ALB Application Load Balancer 를구성해보는과정을정리해봤습니다 사전작업Public에 |
2022-03-09 12:37:59 |
海外TECH |
Ars Technica |
Is Elden Ring really that hard? Well, it depends what you mean by “hard” |
https://arstechnica.com/?p=1839505
|
difficulty |
2022-03-09 12:30:46 |
海外TECH |
Ars Technica |
Florida’s latest anti-health political stunt is to cast doubt on kids’ vaccines |
https://arstechnica.com/?p=1839576
|
figures |
2022-03-09 12:15:15 |
海外TECH |
MakeUseOf |
What Is NVLink and Is It Better Than SLI? |
https://www.makeuseof.com/what-is-nvlink-and-is-it-better-than-sli/
|
nvlink |
2022-03-09 12:30:13 |
海外TECH |
DEV Community |
Create an Open Source Commerce Marketplace: Part 1 |
https://dev.to/medusajs/create-an-open-source-commerce-marketplace-part-1-3m5k
|
Create an Open Source Commerce Marketplace Part Medusa is an open source headless commerce that allows you to create your own store in a matter of minutes Part of what makes Medusa a good choice for your ecommerce store is its extensibility To make things easier for our open source community Adrien de Peretti one of our amazing contributors created a Medusa module that allows you to extend anything and everything you want I ve been looking for an e commerce solution that could provide me with some core features while being fully customisable After some research where I found that none of the present solutions could provide what I needed I chose Medusa as it provided me with many of the needed features while being easy to extend I ended up loving the community atmosphere especially the proximity with the team and have been helping those in the community looking for a similar fully customisable solution by sharing a part of my private project This is how the medusa extender was born ーAdrien de PerettiIn this tutorial you ll learn how to install and set up the Medusa Extender module on your Medusa server You ll then learn how to use its customization abilities to create a marketplace in your store The marketplace will have multiple stores or vendors and each of these stores will be able to add its own products This tutorial will be the first part of a series that will explore all aspects of creating a marketplace What is Medusa ExtenderMedusa Extender is an NPM package that you can add to your Medusa store to extend or customize its functionalities The scope of its customization entails Entities Repositories Services and more In this article we focus on how to create a Marketplace using Medusa Extender however that s not the only use case for Medusa Extender It can be used in many other use cases such as adding custom fields listening to events to perform certain actions like sending emails customizing Medusa s validation of request parameters and more What You ll Be CreatingIn this article and the following parts of this series you ll learn how to create a marketplace using Medusa and Medusa Extender A marketplace is an online store that allows multiple vendors to add their products and sell them A marketplace has a lot of features including managing a vendor s own orders and settings This part of the tutorial will only showcase how to create stores for each user and attach the products they create to that store Code for This TutorialIf you want to follow along you can find the code for this tutorial in this repository Alternatively if you want to install the marketplace into your existing Medusa store you can install the Medusa Marketplace plugin This plugin is created with the code from this tutorial and will be updated with every new part of this series released PrerequisitesBefore you follow along with this tutorial make sure you have A Medusa server instance was installed You can follow along with our easy quickstart guide to learn how you can do that PostgreSQL installed and your Medusa server connected to it Redis installed and your Medusa server connected to it Building the Marketplace Project SetupIn the directory that holds your Medusa server start by installing Medusa Extender using NPM npm i medusa extenderIt s recommended that you use TypeScript in your project to get the full benefits of Medusa Extender To do that create the file tsconfig json in the root of the Medusa project with the following content compilerOptions module CommonJS declaration true emitDecoratorMetadata true experimentalDecorators true allowSyntheticDefaultImports true moduleResolution node target es sourceMap true skipLibCheck true allowJs true outDir dist rootDir esModuleInterop true include src medusa config js exclude dist node modules spec ts Next update the scripts key in package json with the following content scripts seed medusa seed f data seed json build rm rf dist amp amp tsc start npm run build amp amp node dist src main js These scripts will ensure that your TypeScript files will be transpiled before Medusa is run Then create the file main ts in the directory src with the following content import Medusa from medusa extender import express require express async function bootstrap const expressInstance express await new Medusa dirname expressInstance load expressInstance listen gt console info Server successfully started on port bootstrap This file will make sure to load all the customizations you ll add next when you run your Medusa server Now Medusa Extender is fully integrated into your Medusa instance and you can start building the Marketplace Customize the Store EntityYou ll start by customizing the Store entity You ll need to use it later on to add relations between the store entity and the users and products entities By convention customizations using Medusa Extender are organized in a module like structure However this is completely optional In the src directory create the directory modules in which you ll store all the customizations in Then create the directory store inside the modules directory The store directory will hold all customizations related to the Store Create a Store EntityCreate the file src modules store entities store entity ts with the following content import Store as MedusaStore from medusajs medusa dist import Entity JoinColumn OneToMany from typeorm import Entity as MedusaEntity from medusa extender MedusaEntity override MedusaStore Entity export class Store extends MedusaStore TODO add relations This uses the decorator Entity from medusa extender to customize Medusa s Store entity You create a Store class that extends Medusa s Store entity imported as MedusaStore You ll later on edit this entity to add the relations between the store and users and products Create a Store RepositoryNext you need to override Medusa s StoreRepository This repository will return Medusa s Store entity So you need to override it to make sure it returns your Store entity that you just created Create the file src modules store repositories store repository ts with the following content import EntityRepository from typeorm import StoreRepository as MedusaStoreRepository from medusajs medusa dist repositories store import Repository as MedusaRepository Utils from medusa extender import Store from entities store entity MedusaRepository override MedusaStoreRepository EntityRepository Store export default class StoreRepository extends Utils repositoryMixin lt Store MedusaStoreRepository gt MedusaStoreRepository Create the Store ModuleFor now these are the only files you ll add for the store You can create the Store module using these files Create the file src modules store store module ts with the following content import Module from medusa extender import Store from entities store entity import StoreRepository from repositories store repository Module imports Store StoreRepository export class StoreModule This uses the Module decorator from medusa extender and imports the classes you created The last thing left is to import this module and use it with Medusa In src main ts import StoreModule at the beginning of the file import StoreModule from modules store store module Then add the StoreModule in the array passed as a parameter to Medusa load await new Medusa dirname expressInstance load StoreModule This is all that you ll do for now in the Store module In the next sections you ll be adding more classes to it as necessary Customize the User EntityIn this section you ll customize the user entity mainly to link the user to a store Create the User EntityCreate the directory user inside the modules directory and create the file src modules user entities user entity ts with the following content import User as MedusaUser from medusajs medusa dist import Column Entity Index JoinColumn ManyToOne from typeorm import Entity as MedusaEntity from medusa extender import Store from store entities store entity MedusaEntity override MedusaUser Entity export class User extends MedusaUser Index Column nullable false store id string ManyToOne gt Store store gt store members JoinColumn name store id store Store This class will add an additional column store id of type string and will add a relation to the Store entity To add the new column to the user table in the database you need to create a Migration file Create the file src modules user migrations user migration ts with the following content import Migration from medusa extender import MigrationInterface QueryRunner from typeorm Migration export default class addStoreIdToUser implements MigrationInterface name addStoreIdToUser public async up queryRunner QueryRunner Promise lt void gt const query ALTER TABLE public user ADD COLUMN IF NOT EXISTS store id text await queryRunner query query public async down queryRunner QueryRunner Promise lt void gt const query ALTER TABLE public user DROP COLUMN store id await queryRunner query query The migration is created using the Migration decorator from medusa extender Notice that the migration name should end with a JavaScript timestamp based on typeorm s conventions The up method is run if the migration hasn t been run before It will add the column store id to the table user if it doesn t exist You ll also need to add the relation between the Store and the User entities in src modules store entities store entity ts Replace the TODO with the following OneToMany gt User user gt user store JoinColumn name id referencedColumnName store id members User Make sure to import the User entity at the beginning of the file import User from user entities user entity Create the User RepositoryNext you need to override Medusa s UserRepository Create the file src modules user repositories user repository ts with the following content import UserRepository as MedusaUserRepository from medusajs medusa dist repositories user import Repository as MedusaRepository Utils from medusa extender import EntityRepository from typeorm import User from entities user entity MedusaRepository override MedusaUserRepository EntityRepository User export default class UserRepository extends Utils repositoryMixin lt User MedusaUserRepository gt MedusaUserRepository Create the User ServiceNext you need to override Medusa s UserService class Create the file src modules user services user service ts with the following content import Service from medusa extender import EntityManager from typeorm import EventBusService from medusajs medusa dist services event bus import FindConfig from medusajs medusa dist types common import UserService as MedusaUserService from medusajs medusa dist services import User from entities user entity import UserRepository from repositories user repository import MedusaError from medusa core utils type ConstructorParams manager EntityManager userRepository typeof UserRepository eventBusService EventBusService Service override MedusaUserService export default class UserService extends MedusaUserService private readonly manager EntityManager private readonly userRepository typeof UserRepository private readonly eventBus EventBusService constructor private readonly container ConstructorParams super container this manager container manager this userRepository container userRepository this eventBus container eventBusService public async retrieve userId string config FindConfig lt User gt Promise lt User gt const userRepo this manager getCustomRepository this userRepository const validatedId this validateId userId const query this buildQuery id validatedId config const user await userRepo findOne query if user throw new MedusaError MedusaError Types NOT FOUND User with id userId was not found return user as User This uses the Service decorator from medusa extender to override Medusa s UserService The class you create to override it will extend UserService This new class overrides the retrieve method to ensure that the user returned is the new User entity class you created earlier Create a User MiddlewareThe loggedInUser is not available natively in Medusa You ll need to create a Middleware that when a request is authenticated registers the logged in User within the scope Create the file src modules user middlewares user middleware ts with the following content import MedusaAuthenticatedRequest MedusaMiddleware Middleware from medusa extender import NextFunction Response from express import UserService from user services user service Middleware requireAuth true routes method all path export class LoggedInUserMiddleware implements MedusaMiddleware public async consume req MedusaAuthenticatedRequest res Response next NextFunction Promise lt void gt if req user amp amp req user userId const userService req scope resolve userService as UserService const loggedInUser await userService retrieve req user userId select id store id req scope register loggedInUser resolve gt loggedInUser next You can use the Middleware decorator from medusa extender to create a Middleware that runs on specific requests This Middleware is run when the request is received from an authenticated user and it runs for all paths notice the use of path and for all types of requests notice the use of method all Inside the middleware you retrieve the current user ID from the request then retrieve the user model and register it in the scope so that it can be accessed from services This approach is simplified for the purpose of this tutorial However it makes more sense to include this middleware in a separate auth module Whether you include this middleware in the user module or the auth middleware will not affect its functionality Create a Store Service to Handle User Insert EventsYou need to ensure that when a user is created a store is associated with it You can do that by listening to the User created event and creating a new store for that user You ll add this event handler in a StoreService Create the file src modules store services store service ts with the following content import StoreService as MedusaStoreService from medusajs medusa dist services import EntityManager from typeorm import CurrencyRepository from medusajs medusa dist repositories currency import Store from entities store entity import EntityEventType Service MedusaEventHandlerParams OnMedusaEntityEvent from medusa extender import User from user entities user entity import EventBusService from medusajs medusa dist services event bus import StoreRepository from repositories store repository interface ConstructorParams loggedInUser User manager EntityManager storeRepository typeof StoreRepository currencyRepository typeof CurrencyRepository eventBusService EventBusService Service override MedusaStoreService scope SCOPED export default class StoreService extends MedusaStoreService private readonly manager EntityManager private readonly storeRepository typeof StoreRepository constructor private readonly container ConstructorParams super container this manager container manager this storeRepository container storeRepository withTransaction transactionManager EntityManager StoreService if transactionManager return this const cloned new StoreService this container manager transactionManager cloned transactionManager transactionManager return cloned OnMedusaEntityEvent Before Insert User async true public async createStoreForNewUser params MedusaEventHandlerParams lt User Insert gt Promise lt EntityEventType lt User Insert gt gt const event params const createdStore await this withTransaction event manager createForUser event entity if createdStore event entity store id createdStore id return event public async createForUser user User Promise lt Store void gt if user store id return const storeRepo this manager getCustomRepository this storeRepository const store storeRepo create as Store return storeRepo save store public async retrieve relations string if this container loggedInUser return super retrieve relations const storeRepo this manager getCustomRepository this storeRepository const store await storeRepo findOne relations join alias store innerJoin members store members where qb gt qb where members id memberId memberId this container loggedInUser id if store throw new Error Unable to find the user store return store OnMedusaEntityEvent Before Insert is used to add a listener to an insert event on an entity which in this case is the User entity Inside the listener you create the user using the createForUser method This method just uses the StoreRepository to create a store You also add a helper event retrieve to retrieve the store that belongs to the currently logged in user Notice the use of scope SCOPED in the Service decorator This will allow you to access the logged in user you registered earlier in the scope You ll need to import this new class into the StoreModule In src modules store store module ts add the following import at the beginning import StoreService from services store service Then add the StoreService to the imports array passed to Module imports Store StoreRepository StoreService Create a User SubscriberFor the event listener to work you need to first emit this event in a subscriber The event will be emitted before a User is inserted Create the file src modules user subscribers user subscriber ts with the following content import Connection EntitySubscriberInterface EventSubscriber InsertEvent from typeorm import eventEmitter Utils as MedusaUtils OnMedusaEntityEvent from medusa extender import User from entities user entity EventSubscriber export default class UserSubscriber implements EntitySubscriberInterface lt User gt static attachTo connection Connection void MedusaUtils attachOrReplaceEntitySubscriber connection UserSubscriber public listenTo typeof User return User public async beforeInsert event InsertEvent lt User gt Promise lt void gt return await eventEmitter emitAsync OnMedusaEntityEvent Before InsertEvent User event transactionalEntityManager event manager This will create a subscriber using the EventSubscriber decorator from typeorm Then before a user is inserted the OnMedusaEntityEvent Before InsertEvent event from medusa extender is emitted which will trigger creating the store To register the subscriber you need to create a middleware that registers it Create the file src modules user middlewares userSubscriber middleware ts with the following content import MEDUSA RESOLVER KEYS MedusaAuthenticatedRequest MedusaMiddleware Utils as MedusaUtils Middleware from medusa extender import NextFunction Response from express import Connection from typeorm import UserSubscriber from subscribers user subscriber Middleware requireAuth false routes method post path admin users export class AttachUserSubscriberMiddleware implements MedusaMiddleware public async consume req MedusaAuthenticatedRequest res Response next NextFunction Promise lt void gt const connection req scope resolve MEDUSA RESOLVER KEYS manager as connection Connection MedusaUtils attachOrReplaceEntitySubscriber connection UserSubscriber return next This will register the subscriber when a POST request is sent to admin users which creates a new user Create a User RouterThe last customization left is an optional one By default Medusa s create user endpoint requires you to be authenticated as an admin In a marketplace use case you might want users to register on their own and create their own stores If this is not the case for you you can skip creating the following class Medusa Extender allows you to also override routes in Medusa In this case you ll be adding the admin create user route to accept non authenticated requests Create the file src modules user routers user router ts and add the following content import Router from medusa extender import createUserHandler from medusajs medusa dist api routes admin users create user import wrapHandler from medusajs medusa dist api middlewares await middleware Router routes requiredAuth false path admin create user method post handlers wrapHandler createUserHandler export class UserRouter You use the Router decorator from medusa extender to create a router This router will accept a routes array which will either be added or override existing routes in your Medusa server In this case you override the admin create user route and set requiredAuth to false To make sure that the AttachUserSubscriberMiddleware also runs for this new route so that the before insert user event handlers run for this new route make sure to add a new entry to the routes array Middleware requireAuth false routes method post path admin users method post path admin create user Create a User ModuleYou ve added all the customizations necessary to associate a user with their own store Now you can create the User module using these files Create the file src modules user user module ts with the following content import AttachUserSubscriberMiddleware from middlewares userSubscriber middleware import LoggedInUserMiddleware from middlewares loggedInUser middleware import Module from medusa extender import User from entities user entity import UserRepository from repositories user repository import UserRouter from routers user router import UserService from services user service import addStoreIdToUser from migrations user migration Module imports User UserService UserRepository addStoreIdToUser UserRouter LoggedInUserMiddleware AttachUserSubscriberMiddleware export class UserModule If you didn t create the UserRouter in the previous step then make sure to remove it from the imports array The last thing left is to import this Module In src main ts import UserModule at the beginning of the file import UserModule from modules user user module Then add the UserModule in the array passed as a parameter to Medusa load await new Medusa dirname expressInstance load UserModule StoreModule Test it OutYou are now ready to test out this customization In your terminal run your Medusa server npm startOr using Medusa s CLI medusa developAfter your run your server you need to use a tool like Postman to easily send requests to your server If you didn t add the UserRouter you first need to log in as an admin to be able to add users You can do that by sending a POST request to localhost admin auth In the body you should include the email and password If you re using a fresh Medusa install you can use the following credentials email admin medusa test com password supersecret Following this request you can send authenticated requests to the Admin Send a POST request to localhost admin users http localhost admin users to create a new user In the body you need to pass the email and password of the new user email example gmail com password supersecret The request will return a user object with the details of the new user Notice how there s a store id field now If you try to create a couple of users you ll see that the store id will be different each time Customize the Products EntitySimilar to how you just customized the User entity you need to customize the Product entity to also hold the store id with the relationship as well You ll then customize the ProductService as well as other classes to make sure that when a product is created the store ID of the user creating it is attached to it You ll also make sure that when the list of products is fetched only the products that belong to the current user s store are returned Create a Product EntityCreate the file src modules product entities product entity ts with the following content import Product as MedusaProduct from medusajs medusa dist import Column Entity Index JoinColumn ManyToOne from typeorm import Entity as MedusaEntity from medusa extender import Store from store entities store entity MedusaEntity override MedusaProduct Entity export class Product extends MedusaProduct Index Column nullable false store id string ManyToOne gt Store store gt store members JoinColumn name store id referencedColumnName id store Store This will override Medusa s Product entity to add the store id field and relation to the Store entity You need to also reflect this relation in the Store entity so in src modules store entities store entity ts add the following code below the relation with the User entity you previously added OneToMany gt Product product gt product store JoinColumn name id referencedColumnName store id products Product Make sure to import the Product entity at the beginning of the file import Product from product entities product entity Create a Product MigrationNext create the file src modules product migrations product migration ts with the following content import MigrationInterface QueryRunner from typeorm import Migration from medusa extender Migration export default class addStoreIdToProduct implements MigrationInterface name addStoreIdToProduct public async up queryRunner QueryRunner Promise lt void gt const query ALTER TABLE public product ADD COLUMN IF NOT EXISTS store id text await queryRunner query query public async down queryRunner QueryRunner Promise lt void gt const query ALTER TABLE public product DROP COLUMN store id await queryRunner query query This will add a migration that will add the store id column to the product table Create a Product RepositoryNext create the file src modules repositories product repository ts with the following content import Repository as MedusaRepository Utils from medusa extender import EntityRepository from typeorm import ProductRepository as MedusaProductRepository from medusajs medusa dist repositories product import Product from entities product entity MedusaRepository override MedusaProductRepository EntityRepository Product export default class ProductRepository extends Utils repositoryMixin lt Product MedusaProductRepository gt MedusaProductRepository This will override Medusa s ProductRepository to return your new Product entity Create a Product ServiceNow you ll add the customization to ensure that only the products that belong to the currently logged in user are returned when a request is sent Since you created the LoggedInUserMiddleware earlier you can have access to the logged in user from any service through the container object passed to the constructor of the service Create the file src modules product services product service ts with the following content import EntityEventType MedusaEventHandlerParams OnMedusaEntityEvent Service from medusa extender import EntityManager from typeorm import ProductService as MedusaProductService from medusajs medusa dist services import Product from entities product entity import User from user entities user entity import UserService from user services user service type ConstructorParams manager any loggedInUser User productRepository any productVariantRepository any productOptionRepository any eventBusService any productVariantService any productCollectionService any productTypeRepository any productTagRepository any imageRepository any searchService any userService UserService Service scope SCOPED override MedusaProductService export class ProductService extends MedusaProductService readonly manager EntityManager constructor private readonly container ConstructorParams super container this manager container manager prepareListQuery selector object config object object const loggedInUser this container loggedInUser if loggedInUser selector store id loggedInUser store id return super prepareListQuery selector config This will override the prepareListQuery method in Medusa s ProductService which this new class extends to get the logged in user Then if the user is retrieved successfully the key store id is added to the selector object to filter the products by the user s store id Create a Product ModuleThat s all the customization you ll do for now You just need to import all these files into a Product module Create src modules product product module ts with the following content import Module from medusa extender import Product from entities product entity import ProductRepository from repositories product repository import ProductService from services product service import addStoreIdToProduct from migrations product migration Module imports Product ProductRepository ProductService addStoreIdToProduct export class ProductModule Finally import the ProductModule at the beginning of src main ts import ProductModule from modules product product module And add the ProductModule to the array passed to load along with UserModule await new Medusa dirname expressInstance load UserModule ProductModule StoreModule Test it OutYou can go ahead and test it out now Run the server if it isn t running already and log in with the user you created earlier by sending the credentials to localhost admin auth After that send a GET request to localhost admin products You ll receive an empty array of products as the current user does not have any products yet Create a Product SubscriberYou ll now add the necessary customization to attach a store ID to a newly created product To listen to the product created event create the file src modules product subscribers product subscriber ts with the following content import Connection EntitySubscriberInterface EventSubscriber InsertEvent from typeorm import OnMedusaEntityEvent Utils eventEmitter from medusa extender import Product from entities product entity EventSubscriber export default class ProductSubscriber implements EntitySubscriberInterface lt Product gt static attachTo connection Connection void Utils attachOrReplaceEntitySubscriber connection ProductSubscriber public listenTo typeof Product return Product public async beforeInsert event InsertEvent lt Product gt Promise lt void gt return await eventEmitter emitAsync OnMedusaEntityEvent Before InsertEvent Product event transactionalEntityManager event manager Then you need to register this Subscriber using Middleware Create the file src modules product middlewares product middleware ts with the following content import MEDUSA RESOLVER KEYS MedusaAuthenticatedRequest MedusaMiddleware Utils as MedusaUtils Middleware from medusa extender import NextFunction Request Response from express import Connection from typeorm import ProductSubscriber from subscribers product subscriber Middleware requireAuth true routes method post path admin products export default class AttachProductSubscribersMiddleware implements MedusaMiddleware public consume req MedusaAuthenticatedRequest Request res Response next NextFunction void Promise lt void gt const connection req scope resolve MEDUSA RESOLVER KEYS manager as connection Connection MedusaUtils attachOrReplaceEntitySubscriber connection ProductSubscriber return next This will register the subscriber when a POST request is sent to admin products which creates a new product Add Event Listener in Product ServiceNext in src modules product services product service ts add the following inside the class OnMedusaEntityEvent Before Insert Product async true public async attachStoreToProduct params MedusaEventHandlerParams lt Product Insert gt Promise lt EntityEventType lt Product Insert gt gt const event params const loggedInUser this container loggedInUser event entity store id loggedInUser store id return event This will listen to the Insert event using the OnMedusaEntityEvent decorator from medusa extender It will then use the logged in user and attach the user s store id to the newly created product Add Middleware to Product ModuleFinally make sure to import the new middleware at the beginning of src modules product product module ts import AttachProductSubscribersMiddleware from middlewares product middleware Then add it in the imports array passed to Module imports Product ProductRepository ProductService addStoreIdToProduct AttachProductSubscribersMiddleware You re ready to add products into a store now Run the server if it s not running and make sure you re logged in with the user you created earlier Then send a POST request to localhost admin products http localhost admin products with the following body title my product options This is the minimum structure of a product You can rename the title to anything you want After you send the request you should receive a Product object where you can see the store id is set to the same store id of the user you re logged in with Now try sending a GET request to localhost admin products http localhost admin products as you did earlier Instead of an empty array you ll see the product you just added Testing it Out Using Medusa s AdminIf you also have a Medusa Admin instance installed you can also test this out Log in with the user you created earlier and you ll see that you can only see the product they added ConclusionIn this tutorial you learned the first steps of creating a Marketplace using Medusa and Medusa Extender In later points you ll learn about how you can add settings manage orders and more Be sure to support Medusa Extender and check the repository out for more details Should you have any issues or questions related to Medusa then feel free to reach out to the Medusa team via Discord You can also contact Adrien adrienp for more details or help regarding Medusa Extender |
2022-03-09 12:47:49 |
海外TECH |
DEV Community |
React.JS has made its way to the popular-most front-end framework in 2022 |
https://dev.to/rajatchauhan/reactjs-has-made-its-way-to-the-popular-most-front-end-framework-in-2022-51n5
|
React JS has made its way to the popular most front end framework in It is very important to create compelling user interfaces for your web and mobile applications But it is also important to choose a suitable technology to build that The survey by Stackoverflow revealed that ReactJS is used by of professional developers higher than any other technology Also I constituted a poll on LinkedIn to know more about the topmost front end framework to build interactive and scalable user interfaces here is what we ve got However we created a poll on our Reddit community to know what is the prefferd most framework Here are our poll results Discussion Which are the Best Frameworks in ReactJS Vs AngularJS Vs VueJS FreeCodeCamp reddit com Suggest Top Frontend Development Frameworks with Reason Indiewebdev reddit com Let us know what you think of it and share your preferred front end framework choice to build an awesome user interface |
2022-03-09 12:32:42 |
海外TECH |
DEV Community |
3 Minutes to Orbiton JS | The Ultimate JavaScript UI library |
https://dev.to/jimjunior/3-minutes-to-orbiton-js-the-ultimate-javascript-ui-library-3m3f
|
Minutes to Orbiton JS The Ultimate JavaScript UI libraryThe rise of web frameworks has made transformed web development as it was known to be It has made it possible to ship web concepts to other platforms like mobile as desktop With focus on front end development in JavaScript libraries like React Vue js and Angular have played a great role in UI development and are taking the biggest portion of the Developer base But this is changing with new libraries like Svelte JS that are introducing new concepts like compiled frameworks Speaking of new Orbiton JS comes into the picture Its a new JavaScript library for building UI s dubbed as “The Ultimate JavaScript library for building User Interfaces Orbiton JS began as a rendering engine from the Media JS NPM package that was for using built HTML Media elements in a website It was originally known as Pearl JS but due to naming conflicts on NPM it was renamed Orbiton JS being new comes with latest trends in the web development world It is built with for concepts in mind and these include the Performance Size Portability and easy adoption by the community let me explain them in detail Orbiton focuses of Performance mainly to archive this the core team writes code that tries to utilize minimal memory as possible based on how different JavaScript engines like V and Gecko compile and run JavaScript Orbiton s one way data binding also makes sure everything is modular and fast Although Orbiton JS utilizes the Virtual DOM it uses an architecture that keeps operations fast to prevent long loops within your application In an aim to keep performance to the peek the team is developing a new renderer that is built in Rust and compiled to web Assembly and this will be a game changer and will make performance even greater The Orbiton team Also tries to keep Orbiton at a very small size with the core package plus the DOM renderer at only KB which is almost equal to only React s core package without ReactDOM which is around KB plus Orbiton achieves this by using clean code and prevents unnecessary operations When it comes to matters concerning portability Orbiton s core packages is written in universal JavaScript that can run in all JavaScript environments be it Node Deno and in the browser This makes it possible for you to run Orbiton in any platform and Orbiton has the concept of registering a custom renderer making it possible to ship Orbiton in any other platform like mobile Orbiton was also built to easily adopt to the JavaScript Ecosystem by making it easy for Orbiton developers to utilize common JavaScript tools like webpack babel and other tools To archive this Orbiton has a set of utils like the official babel plugin and an SWC plugin comming soon that transform JSX to Orbiton functions Lets also explore some of the amazing features of Orbiton JS Orbiton JS uses a component based system making code reusable and Building UIs easy Its is also written in Typescript so has a seem less integration with typescript making it easy to catch bugs Orbiton JS is also reactive in nature with features like state and other proposed features like Proxy binders Orbiton has also created the Orbiton server package to enable server side Rendering in Orbiton The team is also realizing other amazing features in the major release like Fragments Error boundaries Context Suspense Co current Rendering Directives Lazy Components and Portals Some special features like Proxy binders are also going to be introducedEnough with the talk lets get into developing something with Orbiton As I stated Orbiton utilizes JSX so if you are familiar with HTML or JSX itself your are good to go In order to quickly get started with Orbiton the team provides a quick start template Install the template by running these commands in your terminal npx degit Orbitionjs template my appthen runcd my appnpm installnpm startMake sure you have node js installedYour can now go to the index js file and create an element Creating a simple element in Orbiton is easyimport Orbiton append from “orbiton const Button lt button gt Click Me lt button gt append Button document getElementById “root Since this article is just for introducing Orbiton I wont go into details on how to develop Orbiton Applications You can visit the Official documentation for more on Orbiton JS Or even you can view its Source code on GitHub Lets all show this amazing project support by giving it a star on GitHub or even possibly supporting its creator on patreon Well that s all for today Note The team behind Orbiton States if clearly that Orbiton will not be production ready only until version is released otherwise it s just for development purposes but it can also be used in production though its not encouraged In the next article i will be giving you a detailed look into Orbiton with writing some code |
2022-03-09 12:30:11 |
海外TECH |
DEV Community |
Battle of the JavaScript for loops (for, for…in, for…of, forEach, etc.) |
https://dev.to/duncanmcardle/battle-of-the-javascript-for-loops-for-forin-forof-foreach-etc-4lae
|
Battle of the JavaScript for loops for for…in for…of forEach etc Iterating over objects and arrays is something every developer has to do Whether you re a beginner or a seasoned veteran eventually you re going to have to find something in a larger data set But when iterating looping through something you might find yourself a little lost with all of the options available to you So here s a quick breakdown of the main ones Note This isn t a beginner s introduction to how for loops work but rather a comparison of the for loop options available for the classic for is by far the most common loop It isn t specific to arrays or objects or to any data structure in fact and can be combined with almost anything to create powerful and fast loops so long as you configure them properly Here s a classic for loop in action for loops can be used in conjunction with break continue or return to create some seriously versatile functionality forEachforEach allows you to return an entire entry from an array It s simple and straightforward but doesn t come with the additional break continue and return functionality found with a classic for loop It does however look incredibly clean Think of a forEach loop as being like a cleaner array specific for loop for inThe for in loop allows you to loop through the enumerable properties of an object including those set by the parent prototype if one is present Now unfortunately that s probably not what you want You could put a check in on each iteration to see if the property belongs to the object or its prototype hasOwnProperty would be perfect here but that really damages readability In addition for in loops only return strings so if you re looping through an array which does despite the mention of properties above work you probably don t want to use one of these for offor…of iterates over any enumerable object won t convert the values it finds and does so whilst supporting the functionality of break continue and return Think of for of as being like a cleaner version of the for loop specifically for iterable objects without losing any of the for loop s functionality The Object classOne consistent downside of the above for loops is that their compatibility with objects vary That all changes however with the use of the Object class By using Object we can convert our objects to arrays I promise that ll make sense shortly and then loop through those arrays with all of the above loops Now you ll commonly see forEach used in conjunction with this method but the problem with that is that you lose the ability to break continue or return during the loop For that reason I d recommend considering a classic for loop in conjunction with this method but here s an example of both for completeness note that this example uses Object keys which is covered below Object keys This handy function returns an array of keys found in the specified object Even more handily it only includes keys belonging to the immediate object and not its prototype so that means no more seeing the parent props like we do with for in Object entries This one returns each and every entry in its entirety including both the property and value This can be more helpful if you want to retain the key that you re seeing the value of which you often do Object values As the name suggests this method returns only the values found in an object No index no key just values Wrapping things upYou might have reached this point and be hoping for me to say “So make sure kids that you always use the best loop the But c mon that s rarely how programming works In reality the right approach for you depends entirely on the context Some of the above methods are faster than others some are more useful others are more readable It s up to you to find the right combination of the above but hopefully this has helped you on your way to making that decision |
2022-03-09 12:22:03 |
Apple |
AppleInsider - Frontpage News |
Apple praised and slammed for representation of women at March event |
https://appleinsider.com/articles/22/03/09/apple-praised-and-slammed-for-representation-of-women-at-march-event?utm_medium=rss
|
Apple praised and slammed for representation of women at March eventMore women presented at its March Apple Event than ever before and did so without patronizingly championing the fact Yet behind the scenes the company is still apparently failing its staff in this regard Colleen Novielli product line manager Mac introducing the Mac StudioFour of the seven presenters at Apple s March event and all six developers interviewed were women On the face of it the only sensible comment to make is So what Read more |
2022-03-09 12:52:25 |
海外TECH |
Engadget |
The Morning After: Apple reveals Mac Studio, new iPhone SE and more |
https://www.engadget.com/the-morning-after-apple-reveals-mac-studio-new-i-phone-se-and-more-121523820.html?src=rss
|
The Morning After Apple reveals Mac Studio new iPhone SE and moreApple events can sometimes fizzle out Besides the ceremony of a new iPhone series each year it s a little harder to get excited for Macs and iPads with slightly better chips and minor design tweaks We saw a splash of color and some redesigns in the last year but this March event was packed with devices for elements of the Apple audience that aren t always catered for For them this might be an important Apple reveal I say this in hushed tones as a phone guy but the Mac Studio could be the standout It s a pro level desktop built to showcase Apple s most powerful chip the new M Ultra The company says its new desktop runs up to percent faster than a Mac Pro with its core Intel processor Also counter to some of its laptops it s filled with ports There are four Thunderbolt connections two USB A ports HDMI and Gbps Ethernet Also There s an SD card slot and two additional USB C connectors on the front of the computer The bad news might be that it starts at but it still isn t quite the Mac Pro beast some creatives are waiting on That s quot for another day quot according to Apple Oh and there s a new display to go with it At the other end of the scale the iPhone SE makes a return And it s still got a home button This means it looks like its predecessor mostly However it s now got G welcome to and an updated quad core A Bionic processor ーthe same processor as Apple s iPhone series but now in a phone that costs Finally Apple s iPad Air also sticks to its redesign It has a new front facing camera sensor and like the iPad Pro features Apple s M chip We go into finer detail below or if you need a swift overview we ve pulled all the bullet points together right here ーMat SmithThe biggest stories you might have missedItch io s bundle with almost games will benefit charities helping UkraineGoogle is buying cybersecurity company Mandiant for billionApple discontinues the inch iMacThe new iPhone SE vs the competitionApple s Mac Studio is a tiny pro level desktop powered by M UltraThe new iPad Air gets a big performance boost with Apple s M chipAMD vows to fix Ryzen chip stuttering issues on Windows with new updateThe new iPhone SE adds G but keeps the home buttonApple s budget friendly phone looks exactly like its predecessor AppleAs I mentioned in the intro there are no major design shakeups here The new iPhone SE is a more affordable version of the flagship range now packing an A Bionic processor some new camera tricks despite the single lens and a familiar home button With the upgraded internals including power efficiencies from iOS Apple says we ll see better battery life performance compared to the last model The inch screen is covered with what Apple calls the quot toughest glass in a smartphone on both the front and back quot Continue reading Apple unveils its most powerful chip yet the M UltraIt s basically two M Max chips fused together Following the M M Pro and M Max Apple is adding a new member to the family the M Ultra The M Ultra is essentially two M Max chips put together making it even better for intensive creative applications like video editing and D rendering Apple says the M Max chips feature a die to die interconnect dubbed UltraFusion and its specs are basically what happens when you sandwich two M Max chips the Ultra features a core CPU high performance and high efficiency cores and a core GPU Apple says it should offer up to eight times faster graphics than the original M chip Continue reading Apple announces the inch K Studio Display for Mac StudioIt starts at AppleAs expected Apple is adding a new display to its product lineup The Apple Studio Display is a standalone monitor with a K retina panel with million pixels nits of brightness and P wide color gamut coverage It s more for work less for gaming topping out at a Hz refresh rate We re sure Apple thinks it d go really nicely with a new Mac Studio desktop Continue reading Gogoro unveils the first swappable solid state EV batteryElectric scooters could deliver more range without bigger batteries Some Apple respite Gogoro best known for its scooters and charging stations has announced what it claims is the world s first swappable solid state EV battery Using solid state batteries the lithium ceramic prototype is compatible with Gogoro s current scooters but should deliver a much higher capacity ーthe two companies are targeting kWh versus the kWh of existing hardware The end result is greater range and improved safety Continue reading Eargo review Tiny hearing aids that don t scrimp on featuresIt s closing in on the incumbents EngadgetIn the world of hearing aids Eargo stands out The company operates more like a technology company than a slow plodding medical device provider ーit has a rapid annual release cycle more similar to Apple Samsung and the rest In version it s added customizable sound profiles as well as sound adjustment features to help make the Eargo better fit with your own hearing levels and preferences Continue reading |
2022-03-09 12:15:23 |
ニュース |
BBC News - Home |
UK soldier AWOL amid fears he is heading to Ukraine |
https://www.bbc.co.uk/news/uk-60675671?at_medium=RSS&at_campaign=KARANGA
|
confirms |
2022-03-09 12:05:39 |
ニュース |
BBC News - Home |
Climber dies as 17 people rescued on Ben Nevis |
https://www.bbc.co.uk/news/uk-scotland-highlands-islands-60675661?at_medium=RSS&at_campaign=KARANGA
|
climber |
2022-03-09 12:43:49 |
ニュース |
BBC News - Home |
Ukraine war: Cost of filling diesel family car hits record £90 |
https://www.bbc.co.uk/news/business-60670120?at_medium=RSS&at_campaign=KARANGA
|
budgets |
2022-03-09 12:02:15 |
ニュース |
BBC News - Home |
Ukraine ambassador says even his wife faced delay to get visa when he got the job |
https://www.bbc.co.uk/news/uk-politics-60677273?at_medium=RSS&at_campaign=KARANGA
|
bureaucratic |
2022-03-09 12:46:46 |
ニュース |
BBC News - Home |
War in Ukraine: Russia soon unable to pay its debts, warns agency |
https://www.bbc.co.uk/news/business-60672085?at_medium=RSS&at_campaign=KARANGA
|
fitch |
2022-03-09 12:32:03 |
北海道 |
北海道新聞 |
F1角田「一戦一戦を大事に」 参戦2季目へ意欲 |
https://www.hokkaido-np.co.jp/article/654958/
|
一戦一戦 |
2022-03-09 21:06:25 |
北海道 |
北海道新聞 |
コメダ珈琲店 帯広に開店 十勝初 |
https://www.hokkaido-np.co.jp/article/654969/
|
開店 |
2022-03-09 21:20:00 |
北海道 |
北海道新聞 |
四島免税法、プーチン大統領が署名、発効 |
https://www.hokkaido-np.co.jp/article/654954/
|
署名 |
2022-03-09 21:12:03 |
北海道 |
北海道新聞 |
麻生、岸田派幹部が会食 谷垣Gも、大宏池会に臆測 |
https://www.hokkaido-np.co.jp/article/654967/
|
麻生派 |
2022-03-09 21:18:00 |
北海道 |
北海道新聞 |
帯広市長選、三つどもえの公算大 告示まで1カ月 現職と2新人 公約準備急ぐ |
https://www.hokkaido-np.co.jp/article/654966/
|
三つどもえ |
2022-03-09 21:18:00 |
北海道 |
北海道新聞 |
EU、対ロ追加制裁で合意 ベラルーシ銀行も対象 |
https://www.hokkaido-np.co.jp/article/654953/
|
欧州連合 |
2022-03-09 21:03:34 |
北海道 |
北海道新聞 |
津別の山上木工専務「アトツギ甲子園」決勝へ 「世界一の木製車いす作る」 |
https://www.hokkaido-np.co.jp/article/654823/
|
車いす |
2022-03-09 21:06:17 |
北海道 |
北海道新聞 |
ソ6―1巨(9日) ソフトB松本が5回無失点 |
https://www.hokkaido-np.co.jp/article/654960/
|
無失点 |
2022-03-09 21:05:00 |
北海道 |
北海道新聞 |
トヨタ、避難支援に最大3億円 ウクライナ巡り国連などに寄付 |
https://www.hokkaido-np.co.jp/article/654959/
|
避難 |
2022-03-09 21:04:00 |
北海道 |
北海道新聞 |
原発攻撃「規制の範囲外」 更田委員長 |
https://www.hokkaido-np.co.jp/article/654956/
|
原子力規制委員会 |
2022-03-09 21:03:00 |
コメント
コメントを投稿