teleren/devto huggingface dataset:
Combine Objects In TypeScript
Tags: typescript, javascript
Published: 2021-04-11 20:41:32

{% twitter 1381343242130690055 %}

If you Google how to combine multiple objects into a single object with shared properties, you will get some information back on using the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). Let's look at a basic example of the spread operator with TypeScript.

In this example, we will be creating Super Heros by combining our regular Heros with SuperPowers to result in a single Super Hero.

Begin by creating an Interface for each of the two objects. One object should ideally contain all of the required properties, and our secondary object should contain only optional properties.

Our Hero will be the base object which we will later combine with Super Powers.

```typescript
interface Hero {
  class: "human" | "elf" | "orc",
  baseHealth: number
}
```

Our secondary object Interface, SuperPowers will contain only optional properties describing our possible superpowers. 

```typescript
interface SuperPowers {
  flying?: boolean,
  superSpeed?: boolean,
  strengthMultiplier?: number
}

```

Now, if our human Hero were to fall into a vat of nuclear waste we can only assume they would potentially gain Super Powers. Let's describe an object with the properties of both.

```typescript
interface SuperHero extends Hero, SuperPowers {}
```

Our SuperHero interface simply extends both of our prior definitions, effectively adding them together into this new Interface.

Now we have our definitions, let's create our new _human **Hero**_ and an object containing the _**SuperPowers**_ we plan to add to our _human **Hero**_ later.

```typescript
const human: Hero = {class: "human", baseHealth: 100}
const powers: SuperPowers = {flying: true}
```

Time to combine. Our Hero has fallen into a vat of nuclear waste, what emerges will no longer be a Hero, but a _**SuperHero**_.

```typescript
const superMan: SuperHero = {...human, ...powers}
```

**superMan** will have the following types:
- baseHealth
- class
- flying?
- strengthMultiplier?
- superSpeed?

## Full example

```typescript
interface Hero {
  class: "human" | "elf" | "orc",
  baseHealth: number
}

interface SuperPowers {
  flying?: boolean,
  superSpeed?: boolean,
  strengthMultiplier?: number
}

interface SuperHero extends Hero, SuperPowers {}

const human: Hero = {class: "human", baseHealth: 100}
const powers: SuperPowers = {flying: true}

const superMan: SuperHero = {...human, ...powers}

```

TypeScript Playground: [TS Playground](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgBLQPbIN4ChnIIA2cAzqQFzIBEAFgK4C2cI1yAPjRETG59RigJqAGnzIARmQjo4RMLSogmE6LgC+uXKEixEKAMr0ADtAAKGAO7RSOcTCIBPUAHMA-FQkYMRCCzEEpCbQBqYQACYekt6+-uKkYFAQIC4KALL08sDGRMDQUcqMqlAaWjrQ8EjIRqZQ6FBYEAAekCDhtvUYItXBUBbWULbYmrgIGCAJyAzMIFSdyAC8OMRklDTTLKKS0rLyisgAjAAMR5pjE2DIxlY2VDXmN4OLOA7OKVSJ9BAj55NBtWkWHdevMltgAHSQjYgbqQ8HXAakTQAemRAAEACoQBC0AwAR3owHCGIAakA)
Spread Syntax: [MDN Spread Syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax)
API Authentication using Laravel Sanctum
Tags: laravel, php, restapi, mysql
Published: 2021-04-11 20:38:05

What is Laravel Sanctum?
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities/scopes which specify which actions the tokens are allowed to perform. Here are some reasons you might want to choose Sanctum over Passport:

1. Passport is implemented with OAuth2 authentication. If you are not using that, then Sanctum is your go-to for issuing API tokens.
2. Sanctum is a featherweight, meaning it is light and simple to implement.
3. Sanctum works with SPAs (Single Page Applications like Vue, Angular, and React) and supports mobile application authentication.

https://techvblogs.com/blog/api-authentication-laravel-sanctum
Deploying a SvelteKit app to Netlify
Tags: svelte, sveltekit, netlify, webdev
Published: 2021-04-11 20:29:13

Want to deploy your SvelteKit app to Netlify? Well, you're in luck because it's actually quite easy!

Let's jump right in 👇


---

# 1. Create your SvelteKit project

First, obviously you'll need a SvelteKit project. If you don't have one yet, setup is super simple:

```bash
npm init svelte@next my-app
cd my-app
npm i
```

Then you can run `npm run dev` to play 👯‍♀️ with your new app.

---

# 2. Create `netlify.toml`

You'll need to let Netlify know where the SvelteKit build will be located (`/build`) and where the serverless functions will live (`/functions`).

In the root of your project, create a `netlify.toml` file:

```toml
[build]
  command = "npm run build"
  publish = "build/"
  functions = "functions/"
```

---

# 3. Use the Netlify adapter

Now you'll want to install the [@sveltejs/adapter-netlify adapter](https://www.npmjs.com/package/@sveltejs/adapter-netlify):

```shell
npm i -D @sveltejs/adapter-netlify@next
```

In your `svelte.config.cjs` file, change `adapter-node` to `adapter-netlify`, like so (diff):

```diff
const sveltePreprocess = require('svelte-preprocess')
-const node = require('@sveltejs/adapter-node')
+const netlify = require('@sveltejs/adapter-netlify')
const pkg = require('./package.json')

/** @type {import('@sveltejs/kit').Config} */
module.exports = {
  // Consult https://github.com/sveltejs/svelte-preprocess
  // for more information about preprocessors
  preprocess: sveltePreprocess(),
  kit: {
    // By default, `npm run build` will create a standard Node app.
    // You can create optimized builds for different platforms by
    // specifying a different adapter
-    adapter: node(),
+    adapter: netlify(),

    // hydrate the <div id="svelte"> element in src/app.html
    target: '#svelte',

    vite: {
      ssr: {
        noExternal: Object.keys(pkg.dependencies || {}),
      },
    },
  },
}
```

Now you have everything you need to deploy your Netlify site!

---

# 4. Deploy on Netlify

Now all you need to do is:

1. Create a Github repo
2. Push your code to it
3. Add the new repo to Netlify (e.g. the "New site from Git" button)
  - Accept the default options
4. Wait for it to build and after about a minute, you should have a SvelteKit app on Netlify! 🎉

Now you can add routes to your SvelteKit app and they will be served by Netlify's global serverless infrastructure 🛰

---

# That's it!

Deploying SvelteKit to Netlify (or Vercel) is quite simple and gives you a global CDN and serverless function out the gate!

Hope this was helpful! 🍻

If you want to check out the source code, [see the Github repo here](https://github.com/danawoodman/netlify-sveltekit).


_Follow me on [Dev.to](https://dev.to/danawoodman), [Twitter](https://twitter.com/DanaWoodman) and [Github](https://github.com/danawoodman) for more web dev and startup related content_ 🤓
Disabling Viewport Zoom on iOS 14 Web Browsers
Tags: webdev, css, ios
Published: 2021-04-11 20:13:52

---
title: Disabling Viewport Zoom on iOS 14 Web Browsers
published: true
description: 
tags: webdev,css,ios
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q85p2wx8robpdftjjvsl.jpg
---

I recently answered a question on Discord on how to disable double-tap to zoom on iOS browsers. I looked this problem up on Google, and most people said to use the viewport meta tag. Except that was four years ago and it seems that Safari no longer respects those tags. 

Many are using Javascript to solve this, but that could be unreliable in many ways.

But now, since Safari 13, there is a way to disable viewport zooming.

```css
body {
  touch-action: pan-y;
}
```

What the `touch-action` property does is it disables all touch events going to the selected element(s) except for the value specified. So by setting the property to `pan-y` for the whole body, we're only letting the user pan up and down, no matter where they initiate the touch. Any other touch events, whether it be a double tap, a pinch, or even a pan left or right, will be ignored. 

You can read more about the `touch-action` CSS property [here](https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action)

---

If you need to allow the user to pan both up or down _and_ left or right, you can add `pan-x`:

```css
body {
  touch-action: pan-y, pan-x;
}
```

---

If you have just `pan-y` turned on in your body selector, and you have smaller viewports inside your document where there will be horizontal scrolling, you can override the property value in the child element.

```css
.childViewPortElement {
  overflow: scroll;
   ...
  touch-action: pan-y, pan-x;
}
```

---

## Fair Warning
In my testing I found out that on iOS, viewport zoom is fully disabled when the `touch-action` property is restricted like this. This applies even to automatic zooms that the browser performs, such as when the user taps on a text box with a font size smaller than 16px. 

However, if even one element in the body has `touch-action` set to `pinch-zoom` or `manipulation` the browser will perform automatic zooms when tapping on small text boxes.

So be mindful of that, if you do have to enable manipulation or pinch-zoom events.
Improve performance by deleting laravel log file via Routes. (Artisan & exec)
Tags: laravel, php, artisan
Published: 2021-04-11 20:13:39

Laravel log file helps we developers in so many ways such logging of data and more importantly is that all errors generated by our web application are be logged in our laravel log file which is located at **storage\logs\laravel.log**, this error generated by our web app can make log file size rapidly increasing to like 30GB in size 😲 according to this post => [Laravel log file size rapidly increasing](https://community.librenms.org/t/laravel-log-file-size-rapidly-increasing/7232 ), this can be a bottle neck problem to some simple Laravel application out there that is been hosted in a small web shared hosting site with limit disk space. Instead of using **ssh or filezilla** to delete this log file manually over and over, here i will show you how to do that with via route i.e when you goto **www.yoursite.come/clear or www.yoursite.come/delete** that log file will be deleted and your server will have a breathing space. 👽 

Let get started either by using existing project or creating new project this will still work.

Goto your web.php file and paste this

>Route::get('/clear', function() {
    exec('rm -f ' . storage_path('logs/*.log'));
    exec('rm -f ' . base_path('*.log'));
    return "Log file deleted";
});

To run the Above route goto **www.yoursite.com/clear** and hit enter, BOOM it delete all the log file in **storage_path or base_path.** So also you can change this to any location you log file is kept. 😁

For bonus let me show you a simple way to run Artisan inside route (web.php or api.php) on live production with using terminal. WIth this Artisan command you can optimize your laravel web app.

> Route::get('/cl', function() {
    Artisan::call('config:cache');
    Artisan::call('cache:clear');
    Artisan::call('config:clear');
    Artisan::call('view:clear');
    Artisan::call('route:clear');
    exec('rm -f ' . storage_path('logs/*.log'));
    exec('rm -f ' . base_path('*.log'));
    return "Cache is cleared";
})->name('clear.cache');

Above command helps you to Improve Laravel Performance by removing Config caching, Routes caching and view caching for better loading of your web app. 😜

Post Motivation 
[My laravel.log size is 31 GB](https://laracasts.com/discuss/channels/laravel/my-laravellog-size-is-31-gb#:~:text=log%20size%20is%2031%20GB,-Hello%20everyone%2C%20I). 

For more tutorial share , comment and if any question or suggest drop it.

Follow me on X for more.. [Ejeh on X](https://twitter.com/don_ejeh)
Testing API's JSON response with chai
Tags: chai, mocha, javascript, testing
Published: 2021-04-11 19:37:01

Sometimes we need to validate our API's response if it correctly returning JSON structure.

We may unintended add some secret fields to JSON response such as passwords, tokens.

To be aware of this we should test the JSON response if does it matches our need.

I've wrote chai plugin which helps to test JSON structures with ease.

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hhga7xs1ftp5ekcddz7m.png)  

https://github.com/Adizbek/chai-json-validation

Please rate my work and leave comments below about plugin
Using Docker secrets with MySQL in Docker Compose
Tags: docker, laravel, mysql
Published: 2021-04-11 19:22:16

---
title: Using Docker secrets with MySQL in Docker Compose
published: true
date: 2021-04-11 19:21:48 UTC
tags: docker,laravel,mysql
canonical_url: https://adithya.dev/docker-secrets-with-mysql-in-docker-compose/
---

Prefacing this that Docker secrets were built for Docker Swarm and not for single containers. From the docs:

> **Note** : Docker secrets are only available to swarm services, not to standalone containers. To use this feature, consider adapting your container to run as a service. Stateful containers can typically run with a scale of 1 without changing the container code.

Also, this is not completely secure as we will be using files on the host machine to feed at the build time, so if you're considering commiting this to your repository, commit just the secrets' file structure with no content.

Initial docker container that I used for a Laravel application:

```
mysql:
    image: mysql:8.0.22
    container_name: mysql
    restart: unless-stopped
    tty: true
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3307:3306"
    environment:
      MYSQL_DATABASE: db_name
      MYSQL_USER: user_name
      MYSQL_PASSWORD: db_password
      MYSQL_ROOT_PASSWORD: db_root_password
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
  
```

To use Docker Secrets, we need to create two files (for two passwords). I created it in the same level as the docker-compose.yml inside a folder `secrets` named `db_password.txt` and `db_root_password.txt` (commit at this point) and then add the passwords inside them.

Now let's change the docker container definition to this:

```
mysql:
    image: mysql:8.0.22
    container_name: mysql
    restart: unless-stopped
    tty: true
    volumes:
      - ./mysql:/var/lib/mysql
    ports:
      - "3307:3306"
    environment:
      MYSQL_DATABASE: db_name
      MYSQL_USER: db_user
      MYSQL_PASSWORD_FILE: /run/secrets/db_password
      MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db_root_password
      SERVICE_TAGS: dev
      SERVICE_NAME: mysql
    secrets:
      - db_password
      - db_root_password
      
  
secrets:
  db_password:
    file: ./secrets/db_password.txt
  db_root_password:
    file: ./secrets/db_root_password.txt
```

Define a `secrets` section on your docker-compose.yml with the file locations and then in the `mysql` section, we'll just use those **without** the extension during runtime.

Important thing to note is that `MYSQL_PASSWORD` and `MYSQL_ROOT_PASSWORD` have been replaced by `MYSQL_PASSWORD_FILE` and `MYSQL_ROOT_PASSWORD_FILE`

Run `docker-compose up -d` and your MySQL installation should be using these passwords from the files :)
Wordpress blog in a Rails app subfolder 🙈
Tags: rails, wordpress
Published: 2021-04-11 19:07:12

Hello peeps 👋🏼 

As anyone in the Dev community successfully added a Wordpress blog to a subfolder in a rails app?

myapp.com (rails)
myapp.com/blog (wordpress)

I have done a few rounds of googling but haven’t yielded any confident results.

I am thinking that page rules within Cloudflare might be the answer but apparently Wordpress likes to be at the root domain or subdomain.

I know I could use Rails as the blog but I can’t be 🍑’sed atm as I can just use the huge Wordpress plugin systems for stuff I need quickly.

Thanks 😊 and in return I can do portraits of anyone that can shed clear informations on said subject.
Upserts with PostgREST or Supabase
Tags: supabase, postgres, postgrest
Published: 2021-04-11 19:06:13

I have a table with a UNIQUE INDEX on multiple columns, and I'd like to upsert new values to that table based on that unique constraint.  Can I do this without major contortions?

Game on.

Users can have one pick per event, so the picks table has 4 columns pickid, userid, eventid, pick.  Primary key is unique, and there's also a unique index on userid and eventid.

Now if a user wants to change their pick, I need an upsert (insert if that userid/eventid pair doesn't exist, otherwise update the pick column of the current record.) 

Upserts in PostgreSQL are handled with [ON CONFLICT](https://wiki.postgresql.org/wiki/UPSERT), as follows:
```
INSERT INTO picks (userid, eventid, pick)
VALUES(20, 30,'My pick') 
ON CONFLICT (userid, eventid) 
DO 
   UPDATE SET pick = 'My pick'
```

[PostgREST knows about upserts too, and does the ON CONFLICT part automagically for you](https://postgrest.org/en/v7.0.0/api.html#upsert).  You can set the `Prefer: resolution=merge-duplicates` or `Prefer: resolution=ignore-duplicates` headers. 

Things get a bit tricky when you want to upsert based on that UNIQUE INDEX based on multiple columns.  The automagical upsert works only with primary keys.  If you want it to use another column or multiple columns, pass the `on_conflict` get variable to the PostgREST api, like `on_conflict=userid,eventid`

One more thing though - I'm use the postgrestjs/supabasejs client, so how do I pass on_conflict?  To find out, I heroicly ventured into the postgrest-js source code and found [this wonderful PR to support on_conflict](https://github.com/supabase/postgrest-js/pull/113/files).  So I just need to add an `onConflict` option like so:
```
const { data, error } = await supabase
  .from('picks')
  .insert([{ userid, eventid, pick}], { upsert: true, onConflict: "userid,eventid"})
```
Notice the camelCase instead of the under_line.  (Mental note: it seems camelCase is kind of the preferred naming convention for Javascript libraries.)

That's it!  It works nicely, encapsulating somewhat complex logic with clear, understandable and short code.
I Now Have A Newsletter; See The First Email
Published: 2021-04-11 19:02:32

---
title: I Now Have A Newsletter; See The First Email
published: true
date: 2021-04-11 19:01:21 UTC
tags: 
canonical_url: https://codelab.farai.xyz/posts/meta/my-first-newsletter/
---

After hesitating a lot on making a newsletter, I’m pleased to introduce the [Farai’s Codelab Newsletter](https://buttondown.email/faraiscodelab).

Read the first edition in which [I introduce the myself, newsletter, my current work and future plans](https://buttondown.email/faraiscodelab/archive/my-very-first-newsletter-featuring-intros-and-wips/).

The [newsletter is availible online](https://buttondown.email/faraiscodelab/archive/) as well as an [RSS feed of the emails](https://buttondown.email/faraiscodelab/rss).

Only thing left is to add a fancy subscribe box for the site and to keep it running. My measure of success is when I have to pay for it. Hope to get to that point!

plz subscribe, kthanxbai!
We're going to 💕transcribe💕 and post each 'Privilege in Tech'🎙️ episode
Published: 2021-04-11 18:26:01

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/puunkrwtqbo7k0jmdkya.jpeg)

✨Announcement✨ 

We've created an organization on the DEV.to platform so that we can 💕transcribe💕 and post each episode! 

Alejandra created the #TechPrivilege podcast🎙 under her @sheCodesNow organization in an effort to help the most vulnerable in tech not feel erased. We'll discuss tech media stories and how to support diverse teammates with less privilege. 

Our co-hosts @alejandra_quetzalli, @maggiecodes_, @devpato, @ovflowd, and @lisaychuang, are excited to talk about tech privilege.

We're also excited to let you know that we recently became a 🟣Twitter Spaces host, and we'll continue to host safe rooms for people to talk about what it feels like to be less privileged in tech. 

p.s. Give us a holler if you'd like to be a guest on the podcast!
Building My Portfolio
Tags: portfolio, wordpress, sideprojects
Published: 2021-04-11 18:12:17

<h1>Thoughts</h1>
I've been building my personal website/portfolio using three different methods. First I started using Wix. My first impressions are I thought this was supposed to make building my website easier?? Second, I'm using Wordpress with similar feelings. And lastly I'm using html, bootstrap and Jquery and I'm finding this to be easier then the template sites. Still working through, I will update post once site is live and which method came out on top. Stay tuned!
Remove unused Flatpak Runtimes from Linux

Tags: linux, flatpak
Published: 2021-04-11 18:06:06

Flatpak does not remove dependencies such as runtime components after a certain program is removed, this means if the program has been uninstalled the runtime libraries do not uninstall with it.

This can over time cause massive disk space usage if you heavily rely on it.

[Continue Reading](https://darryldias.me/2021/remove-unused-flatpak-runtimes-from-linux/)
Releases of Perl Distributions Crypt::OpenSSL::PKCS12 and Crypt::OpenSSL::X509
Tags: perl, release, opensource
Published: 2021-04-11 18:02:32

---
title: Releases of Perl Distributions Crypt::OpenSSL::PKCS12 and Crypt::OpenSSL::X509
published: true
description: Maintenance releases of Perl distributions
tags: perl, release, opensource
---
Maintaining a lot of different Perl distributions and open source projects is very time consuming and I do not spend as much time on this as I would like and often I do not pay attention to projects for a long time, unless something pushes me to give proper attention.

Sometimes I am luckly that somebody else provide put in the work, in the form of fixes or PRs and I just have to review and release.

The other day [an issue](https://github.com/dsully/perl-crypt-openssl-x509/issues/81) was created for [Crypt::OpenSSL::X509](https://metacpan.org/pod/Crypt::OpenSSL::X509) by Shoichi Kaji (thanks!). The issue was not a PR, but it did contain a proposal for a solution.

The issue was building the X509 distribution on a M1 Mac with Homebrew. Apparently some of the paths for the C libraries had changed - anyway I got the proposed solution converted into a PR and a release.

Shoichi Kaji was so kind to report back to be that the new release of [Crypt::OpenSSL::X509](https://metacpan.org/pod/Crypt::OpenSSL::X509) was working as expected.

I knew that the same issue would be applicable for [Crypt::OpenSSL::PKCS12](https://metacpan.org/pod/Crypt::OpenSSL::PKCS12), so I created a release of this distribution also.

I am not doing so much active maintenance as I would like on these distributions, but I do release whenever possible and especially if _prodded_.

IMHO contributions are the _energy_ of open source, I know some maintainers and developers are drowning in contributions and the administrative burden of this become overwhelming. At the same time there are a lot of projects, which do not suffer from this. Here every contribution is what keep these projects alive and let others know that the projects are not completely _dead_.

Thanks to all the contributors to open source, your contributions is what keep things going - at least it is for me.