avatarSufyan Maan, M.Eng

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

8645

Abstract

<span class="hljs-keyword">async</span> <span class="hljs-title function_">delete</span>(<span class="hljs-attr">id</span>: <span class="hljs-built_in">string</span>): <span class="hljs-title class_">Promise</span><<span class="hljs-title class_">Item</span>> { <span class="hljs-keyword">const</span> item = <span class="hljs-keyword">await</span> <span class="hljs-variable language_">this</span>.<span class="hljs-property">itemModel</span>.<span class="hljs-title function_">findByIdAndRemove</span>(id); <span class="hljs-keyword">if</span> (!item) { <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">NotFoundException</span>(<span class="hljs-string">'Item not found'</span>); } <span class="hljs-keyword">return</span> item; } }</pre></div><p id="61ef">3. Controller with Validation:</p><p id="425a">Inside <code>item.controller.ts</code>:</p><div id="dace"><pre><span class="hljs-keyword">import</span> { Body, Controller, Get, Post, Put, Delete, Param, NotFoundException, BadRequestException, ParseUUIDPipe } from <span class="hljs-string">'@nestjs/common'</span>; <span class="hljs-keyword">import</span> { CreateItemDto } from <span class="hljs-string">'./create-item.dto'</span>; <span class="hljs-keyword">import</span> { UpdateItemDto } from <span class="hljs-string">'./update-item.dto'</span>; <span class="hljs-keyword">import</span> { ItemService } from <span class="hljs-string">'./item.service'</span>; <span class="hljs-keyword">import</span> { Item } from <span class="hljs-string">'./item.schema'</span>;

<span class="hljs-meta">@Controller(<span class="hljs-string">'items'</span>)</span> export <span class="hljs-keyword">class</span> <span class="hljs-title class_">ItemController</span> { <span class="hljs-keyword">constructor</span>(<span class="hljs-keyword">private</span> readonly itemService: ItemService) { }

<span class="hljs-meta">@Post()</span>
async create(<span class="hljs-meta">@Body()</span> createItemDto: CreateItemDto): Promise&lt;Item&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.itemService.create(createItemDto);
}

<span class="hljs-meta">@Get()</span>
async findAll(): Promise&lt;Item[]&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.itemService.findAll();
}

<span class="hljs-meta">@Get(<span class="hljs-string">':id'</span>)</span>
async findOne(<span class="hljs-meta">@Param(<span class="hljs-string">'id'</span>)</span> id: string): Promise&lt;Item&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.itemService.findOne(id);
}

<span class="hljs-meta">@Put(<span class="hljs-string">':id'</span>)</span>
async update(<span class="hljs-meta">@Param(<span class="hljs-string">'id'</span>)</span> id: string, <span class="hljs-meta">@Body()</span> updateItemDto: UpdateItemDto): Promise&lt;Item&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.itemService.update(id, updateItemDto);
}

<span class="hljs-meta">@Delete(<span class="hljs-string">':id'</span>)</span>
async delete(<span class="hljs-meta">@Param(<span class="hljs-string">'id'</span>)</span> id: string): Promise&lt;Item&gt; {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.itemService.delete(id);
}

}</pre></div><p id="7771">4. Activate auto-validation:</p><p id="61fc">update the fille main.ts</p><div id="fe08"><pre><span class="hljs-keyword">import</span> { <span class="hljs-title class_">NestFactory</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/core'</span>; <span class="hljs-keyword">import</span> { <span class="hljs-title class_">AppModule</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app.module'</span>; <span class="hljs-keyword">import</span> { <span class="hljs-title class_">ValidationPipe</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>;

<span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">bootstrap</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> app = <span class="hljs-keyword">await</span> <span class="hljs-title class_">NestFactory</span>.<span class="hljs-title function_">create</span>(<span class="hljs-title class_">AppModule</span>); app.<span class="hljs-title function_">useGlobalPipes</span>(<span class="hljs-keyword">new</span> <span class="hljs-title class_">ValidationPipe</span>()); <span class="hljs-keyword">await</span> app.<span class="hljs-title function_">listen</span>(<span class="hljs-number">3000</span>); } <span class="hljs-title function_">bootstrap</span>();</pre></div><h1 id="a2cc">Unit Testing:</h1><p id="0fac">1. Setup:</p><p id="23ed">Install required packages:</p><div id="89f0"><pre>npm install @nestjs/testing</pre></div><p id="2a92">2. Testing the Service:</p><p id="bc15">In the <code>item.service.spec.ts</code>:</p><div id="b87f"><pre><span class="hljs-keyword">import</span> { Test, TestingModule } from <span class="hljs-string">'@nestjs/testing'</span>; <span class="hljs-keyword">import</span> { ItemService } from <span class="hljs-string">'./item.service'</span>; <span class="hljs-keyword">import</span> { getModelToken } from <span class="hljs-string">'@nestjs/mongoose'</span>; <span class="hljs-keyword">import</span> { NotFoundException } from <span class="hljs-string">'@nestjs/common'</span>;

describe(<span class="hljs-string">'ItemService'</span>, () => { let service: ItemService; let mockItemModel;

beforeEach(<span class="hljs-keyword">async</span> () => { mockItemModel = { find: jest.fn(), findById: jest.fn(), findByIdAndUpdate: jest.fn(), findByIdAndRemove: jest.fn(), create: jest.fn(), };

<span class="hljs-keyword">const</span> module: TestingModule = <span class="hljs-keyword">await</span> Test.createTestingModule({
  providers: [
    ItemService,
    {
      provide: getModelToken(<span class="hljs-string">'Item'</span>),
      useValue: mockItemModel,
    },
  ],
}).compile();

service = module.<span class="hljs-keyword">get</span>&lt;ItemService&gt;(ItemService);

});

it(<span class="hljs-string">'should be defined'</span>, () => { expect(service).toBeDefined(); });

describe(<span class="hljs-string">'findAll'</span>, () => { it(<span class="hljs-string">'should return an array of items'</span>, <span class="hljs-keyword">async</span> () => { <span class="hljs-keyword">const</span> result = []; mockItemModel.find.mockResolvedValue(result); expect(<span class="hljs-keyword">await</span> service.findAll()).toBe(result); }); });

describe(<span class="hljs-string">'findOne'</span>, () => { it(<span class="hljs-string">'should retrieve an item by its ID'</span>, <span class="hljs-keyword">async</span> () => { <span class="hljs-keyword">const</span> result = { _id: <span class="hljs-string">'some-id'</span>, name: <span class="hljs-string">'ItemName'</span> }; mockItemModel.findById.mockResolvedValue(result); expect(<span class="hljs-keyword">await</span> service.findOne(<span class="hljs-string">'some-id'</span>)).toBe(result); });

it(<span class="hljs-string">'should throw NotFoundException when item does not exist'</span>, <span class="hljs-keyword">async</span> () =&gt; {
  mockItemModel.findById.mockResolvedValue(<span class="hljs-keyword">null</span>);
  <span class="hljs-keyword">await</span> expect(service.findOne(<span class="hljs-string">'some-id'</span>)).rejects.toThrow(NotFoundException);
});

});

describe(<span class="hljs-string">'create'</span>, () => { it(<span class="hljs-string">'should successfully insert an item'</span>, <span class="hljs-keyword">async</span> () => { <span class="hljs-keyword">const</span> createItemDto = { name: <span class="hljs-string">'NewItem'</span> }; mockItemModel.create.mockResolvedValue(createItemDto); expect(<span class="hljs-keyword">await</span> service.create(createItemDto)).toBe(createItemDto); }); });

describe(<span class="hljs-string">'update'</span>, () => { it(<span class="hljs-string">'should update an item'</span>, <span class="hljs-keyword">async</span> () =&

Options

gt; { <span class="hljs-keyword">const</span> result = { _id: <span class="hljs-string">'some-id'</span>, name: <span class="hljs-string">'UpdatedName'</span> }; <span class="hljs-keyword">const</span> updateItemDto = { name: <span class="hljs-string">'UpdatedName'</span> }; mockItemModel.findByIdAndUpdate.mockResolvedValue(result); expect(<span class="hljs-keyword">await</span> service.update(<span class="hljs-string">'some-id'</span>, updateItemDto)).toBe(result); });

it(<span class="hljs-string">'should throw NotFoundException when item does not exist'</span>, <span class="hljs-keyword">async</span> () =&gt; {
  mockItemModel.findByIdAndUpdate.mockResolvedValue(<span class="hljs-keyword">null</span>);
  <span class="hljs-keyword">await</span> expect(service.update(<span class="hljs-string">'some-id'</span>, {})).rejects.toThrow(NotFoundException);
});

});

describe(<span class="hljs-string">'delete'</span>, () => { it(<span class="hljs-string">'should delete an item by its ID'</span>, <span class="hljs-keyword">async</span> () => { <span class="hljs-keyword">const</span> result = { _id: <span class="hljs-string">'some-id'</span>, name: <span class="hljs-string">'ItemToDelete'</span> }; mockItemModel.findByIdAndRemove.mockResolvedValue(result); expect(<span class="hljs-keyword">await</span> service.delete(<span class="hljs-string">'some-id'</span>)).toBe(result); });

it(<span class="hljs-string">'should throw NotFoundException when item does not exist'</span>, <span class="hljs-keyword">async</span> () =&gt; {
  mockItemModel.findByIdAndRemove.mockResolvedValue(<span class="hljs-keyword">null</span>);
  <span class="hljs-keyword">await</span> expect(service.delete(<span class="hljs-string">'some-id'</span>)).rejects.toThrow(NotFoundException);
});

}); });</pre></div><h1 id="ceb6">E2E Testing:</h1><p id="33a2">Testing the Service:</p><p id="4f53">create new file <code>item.e2e-spec.ts</code>:</p><div id="6d4c"><pre><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Test</span>, <span class="hljs-title class_">TestingModule</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/testing'</span>; <span class="hljs-keyword">import</span> { <span class="hljs-title class_">INestApplication</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'@nestjs/common'</span>; <span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> request <span class="hljs-keyword">from</span> <span class="hljs-string">'supertest'</span>; <span class="hljs-keyword">import</span> { <span class="hljs-title class_">AppModule</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'./../src/app.module'</span>;

<span class="hljs-title function_">describe</span>(<span class="hljs-string">'ItemController (e2e)'</span>, <span class="hljs-function">() =></span> { <span class="hljs-keyword">let</span> <span class="hljs-attr">app</span>: <span class="hljs-title class_">INestApplication</span>;

<span class="hljs-title function_">beforeAll</span>(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> <span class="hljs-attr">moduleFixture</span>: <span class="hljs-title class_">TestingModule</span> = <span class="hljs-keyword">await</span> <span class="hljs-title class_">Test</span>.<span class="hljs-title function_">createTestingModule</span>({
        <span class="hljs-attr">imports</span>: [<span class="hljs-title class_">AppModule</span>],
    }).<span class="hljs-title function_">compile</span>();

    app = moduleFixture.<span class="hljs-title function_">createNestApplication</span>();
    <span class="hljs-keyword">await</span> app.<span class="hljs-title function_">init</span>();
});

<span class="hljs-title function_">afterAll</span>(<span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">await</span> app.<span class="hljs-title function_">close</span>();
});

<span class="hljs-title function_">it</span>(<span class="hljs-string">'/items (GET)'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(app.<span class="hljs-title function_">getHttpServer</span>())
        .<span class="hljs-title function_">get</span>(<span class="hljs-string">'/items'</span>)
        .<span class="hljs-title function_">expect</span>(<span class="hljs-number">200</span>);
});

<span class="hljs-keyword">let</span> <span class="hljs-attr">itemId</span>: <span class="hljs-built_in">string</span>;

<span class="hljs-title function_">it</span>(<span class="hljs-string">'/items (POST)'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(app.<span class="hljs-title function_">getHttpServer</span>())
        .<span class="hljs-title function_">post</span>(<span class="hljs-string">'/items'</span>)
        .<span class="hljs-title function_">send</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Sample Item'</span>, <span class="hljs-attr">description</span>: <span class="hljs-string">'Sample Description'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">100</span> })
        .<span class="hljs-title function_">expect</span>(<span class="hljs-number">201</span>)
        .<span class="hljs-title function_">then</span>(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
            itemId = response.<span class="hljs-property">body</span>.<span class="hljs-property">_id</span>; <span class="hljs-comment">// Assuming the response contains the created item with its ID</span>
        });
});

<span class="hljs-title function_">it</span>(<span class="hljs-string">'/items/:id (GET)'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(app.<span class="hljs-title function_">getHttpServer</span>())
        .<span class="hljs-title function_">get</span>(<span class="hljs-string">`/items/<span class="hljs-subst">${itemId}</span>`</span>)
        .<span class="hljs-title function_">expect</span>(<span class="hljs-number">200</span>)
        .<span class="hljs-title function_">expect</span>(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
            <span class="hljs-title function_">expect</span>(response.<span class="hljs-property">body</span>.<span class="hljs-property">name</span>).<span class="hljs-title function_">toEqual</span>(<span class="hljs-string">'Sample Item'</span>);
        });
});

<span class="hljs-title function_">it</span>(<span class="hljs-string">'/items/:id (PUT)'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(app.<span class="hljs-title function_">getHttpServer</span>())
        .<span class="hljs-title function_">put</span>(<span class="hljs-string">`/items/<span class="hljs-subst">${itemId}</span>`</span>)
        .<span class="hljs-title function_">send</span>({ <span class="hljs-attr">name</span>: <span class="hljs-string">'Updated Item'</span> })
        .<span class="hljs-title function_">expect</span>(<span class="hljs-number">200</span>);
});

<span class="hljs-title function_">it</span>(<span class="hljs-string">'/items/:id (DELETE)'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-title function_">request</span>(app.<span class="hljs-title function_">getHttpServer</span>())
        .<span class="hljs-title function_">delete</span>(<span class="hljs-string">`/items/<span class="hljs-subst">${itemId}</span>`</span>)
        .<span class="hljs-title function_">expect</span>(<span class="hljs-number">200</span>);
});

});

</pre></div><h1 id="53b2">Conclusion:</h1><p id="36d8">This is a basic setup to create a CRUD application using NestJS with MongoDB and then test it. You can expand this app by adding validation, error handling, and other features as needed. The combination of NestJS and MongoDB offers powerful capabilities, and testing ensures that your application behaves as expected.</p></article></body>

Here Are the Top 6 Healthiest Foods I Eat Almost Every Day

Let’s see what WHO says.

Photo by Dan Gold on Unsplash

Your diet is a bank account. Good food choices are good investments. — Bethenny Frankel

What consists of a healthy diet?

According to the World Health Organization (WHO), a healthy diet must include the following for adults.

  • Fruits, legumes, vegetables, nuts, and whole grains
  • An adult should eat at least 400g of fruit and vegetables daily, excluding starchy roots (potatoes, sweet potatoes, etc.)
  • Less than 50g of free sugars per day is roughly equal to 12 teaspoons (By mistake, I wrote 12 tablespoons in a tweet that will be approximately 170g — I deleted that one immediately).
  • Free sugars are already added sugars by manufacturers in beverages, syrups, and by nature in honey, fresh fruit juice, etc. Or, in other words, absolutely no white/brown/cane sugar.
  • Less than one teaspoon of salt per day, which is roughly equal to 5g

Now, let’s jump to the learning part of what I consume almost daily. It’s pretty basic food and gives me energy that accommodates my active lifestyle.

Having a varied diet is vital for maintaining a healthy lifestyle. However, given the wealth of currently available knowledge, I wanted to uncover the top 6 most nutritious foods that were also simple to include in one’s diet.

Here are the top 6 foods I eat each day.

1. Eggs

Eggs are a possible way to give your meal additional lasting power and a source of healthy protein.

Evidence suggests that nutrients in eggs may lessen the chance of developing age-related eye problems, which are the most common in adults aged 50 and older.

Approximately 78 cal and 6g of protein may be found in a single egg.

In addition, egg yolks have zeaxanthin, lutein, and antioxidants that are beneficial to maintaining healthy eyes. There is some evidence that lutein can protect your skin from the harmful effects of UV rays.

2. Broccoli & spinach

Broccoli, this leafy superfood, is loaded with vitamins K, C, and A, all of which contribute to healthy bone growth.

Another explanation why broccoli is frequently ranked as the top healthy food is that it contains a good amount of sulforaphane, which is believed to protect against cancer.

Spinach is also a powerful food that helps reduce the risks of high blood sugar, high blood pressure, and even cancer when consumed in moderation. It’s okay for an adult to eat a bowl of spinach daily.

3. Sweet Potatoes

I’m a sweet eater. I love lemon pie and sweet potato pie. — Claude Williams

Every gym person knows the importance of complex carbohydrates, which can only be completed with sweet potatoes.

A single sweet potato, equivalent to roughly a half cup, contains over four times the amount of vitamin A advised daily.

Additionally, it contains some vitamins B5 & B6, vitamin C, vitamin E, manganese, potassium, and many more. These phytonutrients also perform the function of antioxidants, neutralizing the free radicals that might result in illness.

Buy in bulk; they have a good shelf life and consume 0.5–1 daily. I love to bake them.

4. Oats

You have to eat oatmeal, or you’ll dry up. Anybody knows that. — Kay Thompson

Oatmeal is a standard component of the American breakfast and is considered a superfood.

One of the most common deficiencies in our diets is a fiber deficiency, which can be easily remedied by increasing one’s consumption of oats.

Fiber benefits our digestive tracts and waistlines and helps us feel full for longer. These are all highly significant aspects of a breakfast dish.

Oats are one of the top healthiest foods used as the base for various healthy meals.

5. Snow Peas

These snow peas need very little time to prepare, and in addition to being tasty, they may also be enjoyed on their own as a high-protein snack.

The leaves and stems are harvested and served in various dishes when the plant is immature.

The fact that peas were discovered within tombs of pharaohs suggests that the Egyptians held these legumes in holy and high regard.

6. Yogurt

Life is half delicious yogurt, half crap, and your job is to keep the plastic spoon in the yogurt. — Scott Adams

I eat yogurt every day with almost everything. Weirdly, I eat yogurt for breakfast, lunch, and dinner.

I fell in love with eating yogurt when I was a kid; even now, in my early 30s, when I visit my home country, my mother always makes the most delicious homemade yogurt for me. Love!

Yogurt’s probiotic content contributes to the overall health of our digestive systems. Additionally, it has a high calcium content.

The calcium content in only one cup of yogurt is equivalent to about half of the advised daily dose.

Yogurt also delivers potassium, protein, zinc, phosphorus, riboflavin, and vitamin B12. If you want an even more substantial protein boost, eat yogurt, and whenever it’s an option, go for the plain variety.

Thank you for reading; follow me and clap a couple of times. Thanks

As a new reader, please check my holistic health, productivity, and well-being stories reflecting my reviews, observations, and 30+ days of experiments (29 completed so far) to build a sustainable healthy lifestyle.

After 30+ days of challenges to living a healthy and productive life, I wrote my experiential journey. Here are the links for easy access.

3.78 liters of water per day for 30 days, 20+ Squats per day for 30 days, Reading challenge for 30 days, Coffee, Sugar, 2-minute plank daily for 30 days, 20 Push-ups daily for 30 days , Walk 10,000 steps daily for 30 days, Long Walks, Power Nap, Extra Virgin Olive Oil daily for 30 days, No Shampoo for 30 days, Cold Shower for 30 days, 10,000 Steps, Skincare routine for 30 days, Meditation daily for 30 days, Mental Break, Sit-ups, Matcha, 2-Bananas daily for 30 days, Tim Feriss’ Morning Routine for 30 days, Floss daily for 30 days, Lukewarm Lemon Water daily for 30 days, Stretching daily for 30 days

I also wrote about general life philosophy. Here are the links for easy access.

Mental Health/Brain Damage, Hiking, Cofee (New Research), Technology, Healthy Lifestyle, Life Lessons, Productivity, Learning, Money

Disclaimer: My posts do not include professional or health advice. I only document my reviews, observations, experiences, experiments, and perspectives to provide information to create awareness. This post may contain affiliate links.

To get access to unlimited stories, you can also consider signing up to become a Medium member for just $5. If you sign up using my link, I’ll receive a small commission (at no extra cost to you). Thank you!

Related articles

Health
Mindfulness
Technology
Food
Sciecne
Recommended from ReadMedium