Product
Socket Now Supports uv.lock Files
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
micro-transform
Advanced tools
Tiny library to transform object values between different states; serializator and deserializator
Tiny library to transform objects between different states.
Suitable cases: serializing, deserializing, transforming into different shapes.
npm install micro-transform
.setModelConfig
You can use this method to cherry-pick fields from a passed model. Possible values:
true
— this will include the field as is, without any transformations.false
— this will exclude the field, that could be previously added by
asterisk operator or previously in the chain.Promise
, we'll await for it (those are executed
in parallel).import { createTransformer } from "micro-transform";
const userExample = {
id: "id",
createdAt: 1602201600000,
email: "olivia@EXAMPLE.COM",
password: "secret",
};
type User = typeof userExample;
const userSerializer = createTransformer<User>().setModelConfig({
id: true,
email: (user) => user.email.toLowerCase(),
});
const result = await userSerializer.transform(userExample);
// -> { id: "id", email: "olivia@example.com" }
There's a special case for the setModelConfig
: you can pass a key "*"
to include
all fields instead of listing them one by one.
const userSerializer = createTransformer<User>().setModelConfig({
"*": true,
password: false,
});
const result = await userSerializer.transform(userExample);
// -> { id: "id", createdAt: 1602201600000, email: "olivia@EXAMPLE.COM" }
The library ships with a small importable helper that can help you work with the resulting data on the type level:
import type { TransformerResult } from 'micro-transform';
const dateSerializer = createTransformer<User>().setModelConfig({
createdAt: (user) => formatDate(user.createdAt),
});
type SerializedDate = TransformerResult<typeof dateSerializer>;
// { createdAt: string }
.setCustomConfig
With this you can enchance models with new fields. The key would be the new field name. As of values, it pretty much repeats the model config:
false
— that will exclude the custom field previously added in the chain.const userRoleSerializer = createTransformer<User>().setCustomConfig({
role: async (user) => {
return db.fetchRole(user.id);
},
});
const result = await userRoleSerializer.transform(userExample);
// -> { role: "admin" }
Sometimes you need a bit of extra context to transform data. Say, you need user's locale to pick the correct translation, or user's timezone to localize time fields.
In this case you can define context's structure its structure as the second type
argument. You'll then need to pass it to transform
function. If you do this right,
you will be able to read the value in field-level transformer functions:
const userCreationSerializer = createTransformer<
User,
{ timezone: string }
>().setModelConfig({
createdAt: (user, ctx) => formatDate(user.createdAt, ctx.timezone),
});
const result = await userCreationSerializer.transform(userExample, {
timezone: "Europe/Lisbon",
}); // -> { createdAt: "..." }
Since we accept functions on the field-level transformers, you could have made your own solution for nested transformers, but instead we added a built-in solution for that!
You can pass a transformer as field value, and it will:
type UserWithFriends = User & { friends: User[], bestFriend: User };
declare const user: UserWithFriends;
const friendSerializer = createTransformer<User>().setModelConfig({
email: true,
});
const userSerializer = createTransformer<UserWithFriends>().setModelConfig({
id: true,
friends: friendSerializer,
bestFriend: friendSerializer,
});
const serializedUser = await userSerializer.transform(user);
// { id: string, friends: { email: string }[], bestFriend: { email: string } }
As you might have noticed, the basic API involves chaining model configs and custom configs. And, as you might have guessed by the header, all the configs are merged (not replaced), and all the intermediate transformers are immutable.
You can you this to generate configs that are overall very similar, but differ in small details. For example, if you add or remove fields between different API versions, or user groups (admin, public, etc.).
const adminUserSerializer = createTransformer<User>()
.setModelConfig({
"*": true,
})
.setCustomConfig({ role: (user) => db.fetchRole(user.id) });
// Hiding password
const moderatorUserSerializer = adminUserSerializer.setModelConfig({
password: false,
});
// Hiding role
const publicUserSerializer = moderatorUserSerializer.setCustomConfig({
role: false,
});
Validations are out of the scope for this library. There's no validation of the shape of the incoming data. If you pass in garbage, the library will crash, and it's intended.
If you have untrusted/unexpected input, use any of the schema validation libraries out there, like zod, yup, valita and numerous others.
FAQs
Tiny library to transform object values between different states; serializator and deserializator
The npm package micro-transform receives a total of 4 weekly downloads. As such, micro-transform popularity was classified as not popular.
We found that micro-transform demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.