Skip to content

Commit

Permalink
[automated commit] Bump docs to version 1.13.0
Browse files Browse the repository at this point in the history
  • Loading branch information
leorossi authored and github-actions[bot] committed Nov 28, 2023
1 parent e64ddbb commit 894492b
Show file tree
Hide file tree
Showing 152 changed files with 928 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ And finally, all Platformatic components can be deployed on [Platformatic Cloud]

A Platformatic Service is an HTTP server based on [Fastify](https://www.fastify.io/) that allows developers to build robust APIs with Node.js.
With Platformatic Service you can:
- Add custom functionality in a [Fastify plugin](https://www.fastify.io/docs/latest/Plugins/)
- Add custom functionality in a [Fastify plugin](https://fastify.dev/docs/latest/Reference/Plugins)
- Write plugins in JavaScript or [TypeScript](https://www.typescriptlang.org/)
- Optionally user TypeScript to write your application code

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,11 @@ async function foo (app, opts) {
return text
})

await platformaticService(app, opts)
await app.register(platformaticService, opts)

app.get('/', async (request, reply) => {
return 'Your new root endpoint'
})
}

foo.configType = 'foo'
Expand Down Expand Up @@ -133,5 +137,3 @@ await start(base, process.argv.splice(2)).catch(printAndExitLoadConfigError)
```

This is the same as running with platformatic CLI, the `platformatic.json` file will be loaded from the current directory.


183 changes: 183 additions & 0 deletions versioned_docs/version-1.13.0/guides/environment-variables.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import NewApiProjectInstructions from '../getting-started/new-api-project-instructions.md';

# Using Environment Variables with Platformatic

Applications built with Platformatic loosely follows [the twelve factor app methodology](https://12factor.net/).
This guide will show how to make your application [configurable](https://12factor.net/config), while
keeping your deployment environments as close as possible.

## Environment Variables replacement

In any Platformatic configuration file, you can always interpolate an environment variable inside a value:

```json
{
...
"db": {
"connectionString": "{DATABASE_URL}"
}
...
}
```

The replacement is done via [`pupa`](http://npm.im/pupa), before the JSON file is parsed.

All Platformatic configuration files support Environment Variables replacement, i.e.
env variables are supported in Platformatic Service, Platformatic DB, Platformatic Composer, Platformatic Runtime.

### dotenv support

[`dotenv`](http://npm.im/dotenv) is built in inside Platformatic, allowing you to create an envfile with
all your environment variables, that is loaded automatically by Platformatic at startup.
If a `.env` file exists it will automatically be loaded by Platformatic using
[`dotenv`](https://github.com/motdotla/dotenv). For example:

```plaintext title=".env"
DATABASE_URL=sqlite://./db.sqlite
```

The `.env` file must be located in the same folder as the Platformatic configuration
file or in the current working directory.

Environment variables can also be set directly on the command line, for example:

```bash
PLT_SERVER_LOGGER_LEVEL=debug npx platformatic start
```

### Allowed Environment Variables

All placeholders in a configuration must be available as an environment variable
and must meet the allowed placeholder name rules.

### Allowed placeholder names

Only placeholder names prefixed with `PLT_`, or that are in this allow list, will be
dynamically replaced in the configuration file:

- `PORT`
- `DATABASE_URL`

This restriction is to avoid accidentally exposing system environment variables.
An error will be raised by Platformatic if it finds a configuration placeholder
that isn't allowed.

The default allow list can be extended by passing a `--allow-env` CLI option with a
comma separated list of strings, for example:

```bash
npx platformatic start --allow-env=HOST,SERVER_LOGGER_LEVEL
```

If `--allow-env` is passed as an option to the CLI, it will be merged with the
default allow list.

### Placeholder wildcard

You're also able to define a placeholder wildcard, with your own prefix, for example:

```bash
npx platformatic service start --allow-env=MY_NS_*
# OR
npx platformatic start --allow-env=MY_NS_*
```

This will allow you to use placeholders like `{MY_NS_MY_VAR}`.

## Adding a custom environment variable to a project

### Create a Platformatic DB App

<NewApiProjectInstructions/>

This same tutorial applies to all other Platformatic tools.

### Modify `platformatic.db.json`

Add a `greeting` option inside your `plugins` configuration:

```json
{
...
"plugins": {
"paths": [
{
"path": "./plugins",
"encapsulate": false,
"options": {
"greeting": "{PLT_GREETING}"
}
},
{
"path": "./routes"
}
]
},
...
}
```

This new options will be available inside all the options passed to
all plugins in the `plugins/` folder.

### Decorate the Fastify instance

Create a new `plugins/greeting.js` file, calling [fastify.decorate()](https://fastify.dev/docs/latest/Reference/Decorators/#decorators)
to expose some functionality to other plugins:

```js
/// <reference path="../global.d.ts" />
'use strict'
/** @param {import('fastify').FastifyInstance} fastify */
module.exports = async function (fastify, opts) {
fastify.decorate('sayHello', sayHello)

function sayHello (name) {
return `${opts.greeting} ${name}`
}
}
```

### Use it inside a route

Create a new `routes/hello.js` file that uses the newly added functionality, like so:

```js
/// <reference path="../global.d.ts" />
'use strict'
/** @param {import('fastify').FastifyInstance} fastify */
module.exports = async function (fastify, opts) {
fastify.get('/hello', {
schema: {
querystring: {
type: 'object',
properties: {
name: { type: 'string' }
}
},
required: ['name']
}
}, async (request, reply) => {
return fastify.sayHello(request.query.name)
})
}
```

### Add an environemnt variable

Edit your `.env` file and add:

```
PLT_GREETING=Hello
```

Don't forget to add a default value to your `.env.sample`, as
the `.env` file is not committed to the repository.

### Run your application and test the new route

Run your application with `npm start`, and then test the new route with:

```bash
curl 'http://localhost:3042/hello?name=matteo'
```
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,38 @@ an instance of [`@platformatic/sql-mapper`](/reference/sql-mapper/introduction.m
```javascript title="seed.js"
'use strict'

module.exports = async function ({ entities, db, sql }) {
module.exports = async function seed ({ entities, db, sql }) {
await entities.graph.save({ input: { name: 'Hello' } })
await db.query(sql`
INSERT INTO graphs (name) VALUES ('Hello 2');
`)
}
```

For Typescript use the following stub

```typescript title="seed.ts"
/// <reference path="./global.d.ts" />
import { Entities } from '@platformatic/sql-mapper'

const movies: object[] = [
{ title: 'Harry Potter' },
{ title: 'The Matrix' }
]

export async function seed (opts: { entities: Entities }) {
for (const movie of movies) {
await opts.entities.movie.save({ input: movie })
}
}
```

:::info
Platformatic code will look for a `default` or `seed` function name when importing the file. Take a look at the `execute` function [here](https://github.com/platformatic/platformatic/blob/main/packages/db/lib/seed.mjs)
:::



We can then run the seed script with the Platformatic CLI:

```bash
Expand Down
Loading

0 comments on commit 894492b

Please sign in to comment.